Answer to Exercise 72

| ANSWER TO EXERCISE 72
| The time of day will be returned as a number in the usual Inform time format: as hours times 60 plus minutes (on the 24-hour clock, so that the 'hour' part is between 0 and 23).
    Constant TWELVE_HOURS = 720;
    [ NumericTime hr mn word x;
      if (hr>=24) return -1;
      if (mn>=60) return -1;
      x=hr*60+mn; if (hr>=13) return x;
      x=x%TWELVE_HOURS; if (word=='pm') x=x+TWELVE_HOURS;
      if (word~='am' or 'pm' && hr==12) x=x+TWELVE_HOURS;
      return x;
    ];
    [ MyTryNumber wordnum i j;
      i=wn; wn=wordnum; j=NextWordStopped(); wn=i;
      switch(j)
      {   'twenty-five': return 25;
          'thirty': return 30;
          default: return TryNumber(wordnum);
      }
    ];
    [ TimeOfDay i j k flag loop ch hr mn;
      i=NextWord();
      switch(i)
      {  'midnight': parsed_number=0; return 1;
         'midday', 'noon': parsed_number=TWELVE_HOURS; return 1;
      }
      !   Next try the format 12:02
      j=WordAddress(wn-1); k=WordLength(wn-1);
      flag=0;
      for (loop=0:loop<k:loop++)
      {   ch=j->loop;
          if (ch==':' && flag==0 && loop~=0 && loop~=k-1) flag=1;
          else { if (ch<'0') flag=-1; if (ch>'9') flag=-1; }
      }
      if (k<3) flag=0; if (k>5) flag=0;
      if (flag==1)
      {   for (loop=0:j->loop~=':':loop++, hr=hr*10)
              hr=hr+j->loop-'0';
          hr=hr/10;
          for (loop++:loop<k:loop++, mn=mn*10)
              mn=mn+j->loop-'0';
          mn=mn/10;
          j=NextWordStopped();
          parsed_number=NumericTime(hr, mn, j);
          if (parsed_number<0) return -1;
          if (j~='pm' or 'am') wn--;
          return 1;
      }
      !   Next the format "half past 12"
      j=-1; if (i=='half') j=30; if (i=='quarter') j=15;
      if (j<0) j=MyTryNumber(wn-1); if (j<0) return -1;
      if (j>=60) return -1;
      k=NextWordStopped();
      if (k==-1)
      {   hr=j; if (hr>12) return -1; jump TimeFound; }
      if (k=='o^clock' or 'am' or 'pm')
      {   hr=j; if (hr>12) return -1; jump TimeFound; }
      if (k=='to' or 'past')
      {   mn=j; hr=MyTryNumber(wn);
          if (hr<=0)
          {   switch(NextWordStopped())
              {   'noon', 'midday': hr=12;
                  'midnight': hr=0;
                  default: return -1;
              }
          }
          if (hr>=13) return -1;
          if (k=='to') { mn=60-mn; hr=hr-1; if (hr==-1) hr=23; }
          wn++; k=NextWordStopped();
          jump TimeFound;
      }
      hr=j; mn=MyTryNumber(--wn);
      if (mn<0) return -1; if (mn>=60) return -1;
      wn++; k=NextWordStopped();
     .TimeFound;
      parsed_number = NumericTime(hr, mn, k);
      if (parsed_number<0) return -1;
      if (k~='pm' or 'am' or 'o^clock') wn--;
      return 1;
    ];

Back to the exercise in section 27

Mechanically translated to HTML from third edition as revised 16 May 1997. Copyright © Graham Nelson 1993, 1994, 1995, 1996, 1997: all rights reserved.