factor/basis/roman/roman.factor

74 lines
1.7 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2007 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
USING: accessors arrays assocs fry generalizations grouping
kernel lexer macros make math math.order math.vectors
namespaces parser quotations sequences sequences.private
splitting.monotonic stack-checker strings unicode.case
words effects ;
2007-09-20 18:09:08 -04:00
IN: roman
<PRIVATE
2008-10-21 21:30:26 -04:00
2009-03-27 19:55:43 -04:00
CONSTANT: roman-digits
{ "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" }
2007-09-20 18:09:08 -04:00
2009-03-27 19:55:43 -04:00
CONSTANT: roman-values
{ 1000 900 500 400 100 90 50 40 10 9 5 4 1 }
2007-09-20 18:09:08 -04:00
2008-09-09 15:57:23 -04:00
ERROR: roman-range-error n ;
2007-09-20 18:09:08 -04:00
: roman-range-check ( n -- )
2008-09-09 15:57:23 -04:00
dup 1 3999 between? [ drop ] [ roman-range-error ] if ;
2007-09-20 18:09:08 -04:00
2009-03-27 21:04:05 -04:00
: roman-digit-index ( ch -- n )
1string roman-digits index ; inline
2007-09-20 18:09:08 -04:00
: roman<= ( ch1 ch2 -- ? )
2009-03-27 21:04:05 -04:00
[ roman-digit-index ] bi@ >= ;
2007-09-20 18:09:08 -04:00
: roman>n ( ch -- n )
2009-03-27 21:04:05 -04:00
roman-digit-index roman-values nth ;
2007-09-20 18:09:08 -04:00
: (>roman) ( n -- )
roman-values roman-digits [
2008-12-14 01:37:37 -05:00
[ /mod swap ] dip <repetition> concat %
2007-09-20 18:09:08 -04:00
] 2each drop ;
: (roman>) ( seq -- n )
2009-03-27 21:04:05 -04:00
[ [ roman>n ] map ] [ all-eq? ] bi
[ sum ] [ first2 swap - ] if ;
2008-10-21 21:30:26 -04:00
2007-09-20 18:09:08 -04:00
PRIVATE>
: >roman ( n -- str )
dup roman-range-check [ (>roman) ] "" make ;
2007-09-20 18:09:08 -04:00
: >ROMAN ( n -- str ) >roman >upper ;
: roman> ( str -- n )
>lower [ roman<= ] monotonic-split [ (roman>) ] sigma ;
2007-09-20 18:09:08 -04:00
<PRIVATE
2008-10-21 21:30:26 -04:00
MACRO: binary-roman-op ( quot -- quot' )
2009-03-28 16:02:28 -04:00
[ infer in>> ] [ ] [ infer out>> ] tri
'[ [ roman> ] _ napply @ [ >roman ] _ napply ] ;
2008-10-21 21:30:26 -04:00
2007-09-20 18:09:08 -04:00
PRIVATE>
<<
SYNTAX: ROMAN-OP:
scan-word [ name>> "roman" prepend create-in ] keep
1quotation '[ _ binary-roman-op ]
dup infer [ in>> ] [ out>> ] bi
[ "string" <repetition> ] bi@ <effect> define-declared ;
>>
ROMAN-OP: +
ROMAN-OP: -
ROMAN-OP: *
ROMAN-OP: /i
ROMAN-OP: /mod
2008-10-21 21:30:26 -04:00
SYNTAX: ROMAN: scan roman> parsed ;