]> gitweb.factorcode.org Git - factor.git/blob - extra/roman/roman.factor
Updating code for make and fry changes
[factor.git] / extra / roman / roman.factor
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 sequences.lib
5 sequences.private strings unicode.case ;
6 IN: roman
7
8 <PRIVATE
9 : roman-digits ( -- seq )
10     { "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" } ;
11
12 : roman-values ( -- seq )
13     { 1000 900 500 400 100 90 50 40 10 9 5 4 1 } ;
14
15 ERROR: roman-range-error n ;
16
17 : roman-range-check ( n -- )
18     dup 1 3999 between? [ drop ] [ roman-range-error ] if ;
19
20 : roman<= ( ch1 ch2 -- ? )
21     [ 1string roman-digits index ] bi@ >= ;
22
23 : roman>n ( ch -- n )
24     1string roman-digits index roman-values nth ;
25
26 : (>roman) ( n -- )
27     roman-values roman-digits [
28         >r /mod swap r> <repetition> concat %
29     ] 2each drop ;
30
31 : (roman>) ( seq -- n )
32     dup [ roman>n ] map swap all-eq? [
33         sum
34     ] [
35         first2 swap -
36     ] if ;
37 PRIVATE>
38
39 : >roman ( n -- str )
40     dup roman-range-check [
41         (>roman)
42     ] "" make ;
43
44 : >ROMAN ( n -- str ) >roman >upper ;
45
46 : roman> ( str -- n )
47     >lower [ roman<= ] monotonic-split [
48         (roman>)
49     ] map sum ;
50
51 <PRIVATE
52 : 2roman> ( str1 str2 -- m n )
53     [ roman> ] bi@ ;
54
55 : binary-roman-op ( str1 str2 quot -- str3 )
56     >r 2roman> r> call >roman ; inline
57 PRIVATE>
58
59 : roman+ ( str1 str2 -- str3 )
60     [ + ] binary-roman-op ;
61
62 : roman- ( str1 str2 -- str3 )
63     [ - ] binary-roman-op ;
64
65 : roman* ( str1 str2 -- str3 )
66     [ * ] binary-roman-op ;
67
68 : roman/i ( str1 str2 -- str3 )
69     [ /i ] binary-roman-op ;
70
71 : roman/mod ( str1 str2 -- str3 str4 )
72     [ /mod ] binary-roman-op >r >roman r> ;