I would like to implement a DSL for setting port numbers on a socket object.
I would like the DSL to follow this API for setting the host port number:
host: 8080
If this were a string operation (such as host: localhost
) I could use parse-word
. That's less than ideal though, since Forth is very good at parsing numbers, and re-inventing the wheel is a bad thing.
Are there any standard words in Forth that take the first item on the input string, parse it to a number and push it on the stack?
>NUMBER
is an ANS word (in CORE) that turns strings into numbers, but it's cumbersome to use. Your Forth probably has a more flexible variant. Your Forth probably also supports syntax like #16
$10
%10000
, which all evaluate to 16, regardless of BASE
. So one way to do this:
: parse-num ( "number" -- n | d | r ) parse-word evaluate ;
Or with >NUMBER
, and only returning a single-cell number:
: parse-num ( "number" -- n )
0. parse-word >number ( d c-addr u )
abort" not a number" drop
abort" double received where single-cell number expected" ;
Which aborts if the returned string isn't the empty string that would result if the entire output of PARSE-WORD
was converted into a number, or if the high bits of the double aren't 0, which would be the case if a number not representable by a cell were entered. (NB. >NUMBER
doesn't handle double-number syntax either. It will stop parsing 1.
at the dot. It doesn't even handle negative numbers.)