factor/library/syntax/parse-numbers.factor

51 lines
1.3 KiB
Factor
Raw Normal View History

2005-04-02 02:39:33 -05:00
! Copyright (C) 2004, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: parser
2005-04-02 02:39:33 -05:00
USING: errors generic kernel math sequences strings ;
! Number parsing
: not-a-number "Not a number" throw ;
GENERIC: digit> ( ch -- n )
M: digit digit> CHAR: 0 - ;
M: letter digit> CHAR: a - 10 + ;
M: LETTER digit> CHAR: A - 10 + ;
M: object digit> not-a-number ;
2004-12-16 18:36:26 -05:00
: digit+ ( num digit base -- num )
2dup < [ rot * + ] [ not-a-number ] ifte ;
: (base>) ( base str -- num )
dup string-length 0 = [
not-a-number
] [
2005-04-02 02:39:33 -05:00
0 swap [ digit> pick digit+ ] seq-each nip
] ifte ;
: base> ( str base -- num )
#! Convert a string to an integer. Throw an error if
#! conversion fails.
swap "-" ?string-head [ (base>) neg ] [ (base>) ] ifte ;
2004-07-31 14:58:16 -04:00
2004-12-16 18:36:26 -05:00
GENERIC: str>number ( str -- num )
M: string str>number 10 base> ;
PREDICATE: string potential-ratio "/" swap string-contains? ;
2004-12-16 18:36:26 -05:00
M: potential-ratio str>number ( str -- num )
dup CHAR: / index-of string// swap 10 base> swap 10 base> / ;
2004-08-04 22:43:58 -04:00
PREDICATE: string potential-float "." swap string-contains? ;
2004-12-16 18:36:26 -05:00
M: potential-float str>number ( str -- num )
str>float ;
2004-08-04 22:43:58 -04:00
: parse-number ( str -- num )
#! Convert a string to a number; return f on error.
[ str>number ] [ [ drop f ] when ] catch ;
: bin> 2 base> ;
: oct> 8 base> ;
: dec> 10 base> ;
: hex> 16 base> ;