Sujet : Re: Parsing timestamps?
De : amalawi (at) *nospam* gmail.com (alaa)
Groupes : comp.lang.forthDate : 09. Oct 2024, 16:27:46
Autres entêtes
Organisation : novaBBS
Message-ID : <72c9670d5935524d42be0ef5c6c48338@www.novabbs.com>
References : 1
User-Agent : Rocksolid Light
Hi,
here is another way, which was fun:
\
https://www.novabbs.com/devel/article-flat.php?id=28040&group=comp.lang.forth#28040VOCABULARY timestamps-parser ALSO timestamps-parser DEFINITIONS
\ Idea: parse backward
VARIABLE a VARIABLE n
: >an n ! a ! ; : /an 0 a ! 0 n ! ;
: ch ( -- c ) a @ n @ + 1- C@ ;
: more? ( -- t/f ) n @ 0<> ;
: ch+ ( -- ) more? NOT ABORT" exceeded string" -1 n +! ;
: colon ( -- ) more? IF ch ':' <> ABORT" Expected colon!" ch+ THEN ;
: d? ( c -- t/f ) '0' '9' 1+ WITHIN ;
: digit? ( c -- t/f ) d? NOT ABORT" Expected a digit!" ;
: d ( -- ) ch digit? ch 48 - ch+ ;
: [d] ( -- n ) ch d? IF ch 48 - ch+ ELSE 0 THEN ;
: hr ( -- n ) [d] [d] 10 * + ; : min ( -- n ) [d] [d] 10 * + ; : sec (
-- n ) d [d] 10 * + ;
: parse ( a n -- s m h ) >an sec colon min colon hr /an ;
: .hr ( n -- ) ?DUP IF . ." hr " THEN ;
: .min ( n -- ) ?DUP IF . ." min " THEN ;
: .sec ( n -- ) ?DUP IF . ." sec " THEN ;
: .ts ( s m h -- ) .hr .min .sec ;
\ Examples
: e1 S" 1:2:3" ; CR e1 type e1 parse .s .ts
: e2 S" 02:03" ; CR CR e2 type e2 parse .s .ts
: e3 S" 03" ; CR CR e3 type e3 parse .s .ts
: e4 S" 23:59:59" ; CR CR e4 type e4 parse .s .ts
: e5 S" 0:00:03" ; CR CR e5 type e5 parse .s .ts
: e6 S" " ; CR CR e6 type e6 parse .s .ts \ will fail since we expect at
least one digit with 'd' word, we can use '[d]' for optional digit
\ another stupid idea/hack to try: count ':', replace them with BL,
Evaluate string, push missing fields as zeros