1 ! Copyright (C) 2007 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs kernel math math.order math.vectors
4 namespaces make quotations sequences splitting.monotonic
5 sequences.private strings unicode.case lexer parser
11 : roman-digits ( -- seq )
12 { "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" } ;
14 : roman-values ( -- seq )
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 -- )
20 dup 1 3999 between? [ drop ] [ roman-range-error ] if ;
22 : roman<= ( ch1 ch2 -- ? )
23 [ 1string roman-digits index ] bi@ >= ;
26 1string roman-digits index roman-values nth ;
29 roman-values roman-digits [
30 [ /mod swap ] dip <repetition> concat %
33 : (roman>) ( seq -- n )
34 dup [ roman>n ] map swap all-eq? [
44 [ (>roman) ] "" make ;
46 : >ROMAN ( n -- str ) >roman >upper ;
49 >lower [ roman<= ] monotonic-split
54 : 2roman> ( str1 str2 -- m n )
57 : binary-roman-op ( str1 str2 quot -- str3 )
58 [ 2roman> ] dip call >roman ; inline
62 : roman+ ( str1 str2 -- str3 )
63 [ + ] binary-roman-op ;
65 : roman- ( str1 str2 -- str3 )
66 [ - ] binary-roman-op ;
68 : roman* ( str1 str2 -- str3 )
69 [ * ] binary-roman-op ;
71 : roman/i ( str1 str2 -- str3 )
72 [ /i ] binary-roman-op ;
74 : roman/mod ( str1 str2 -- str3 str4 )
75 [ /mod ] binary-roman-op [ >roman ] dip ;
77 : ROMAN: scan roman> parsed ; parsing