1 ! Copyright (C) 2007 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays assocs effects fry generalizations
4 grouping kernel lexer macros math math.order math.vectors
5 namespaces parser quotations sequences sequences.private
6 splitting.monotonic stack-checker strings unicode.case words ;
11 CONSTANT: roman-digits
12 { "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" }
14 CONSTANT: roman-values
15 { 1000 900 500 400 100 90 50 40 10 9 5 4 1 }
17 ERROR: roman-range-error n ;
19 : roman-range-check ( n -- n )
20 dup 1 10000 between? [ roman-range-error ] unless ;
22 : roman-digit-index ( ch -- n )
23 1string roman-digits index ; inline
25 : roman>= ( ch1 ch2 -- ? )
26 [ roman-digit-index ] bi@ >= ;
29 roman-digit-index roman-values nth ;
31 : (roman>) ( seq -- n )
32 [ [ roman>n ] map ] [ all-eq? ] bi
33 [ sum ] [ first2 swap - ] if ;
39 roman-values roman-digits [
40 [ /mod swap ] dip <repetition> concat
41 ] 2map "" concat-as nip ;
43 : >ROMAN ( n -- str ) >roman >upper ;
46 >lower [ roman>= ] monotonic-split [ (roman>) ] map-sum ;
50 MACRO: binary-roman-op ( quot -- quot' )
51 [ infer in>> length ] [ ] [ infer out>> length ] tri
52 '[ [ roman> ] _ napply @ [ >roman ] _ napply ] ;
59 scan-word [ name>> "roman" prepend create-in ] keep
60 1quotation '[ _ binary-roman-op ]
61 dup infer define-declared ;
71 SYNTAX: ROMAN: scan roman> suffix! ;