fork download
  1. -- Convert numbers to Roman
  2.  
  3. -- Sometimes, complicated if and case constructs can be encoded as data,
  4. -- thus leaving the algorithm itself a simple 'map' operation
  5. -- In the following example, the variable 'digitPattern' encodes the
  6. -- 'subtraction rule' and 'five rule' of the roman number system
  7. -- which otherwise would have to be encoded with tedious 'if' and 'case'
  8.  
  9. -- See jsfiddle.net / rplantiko/ehL5qwpq/ for the original JS version
  10.  
  11. toRoman n =
  12. let
  13. digitPattern = [ [], [0], [0,0], [0,0,0], [0,1],
  14. [1], [1,0], [1,0,0], [1,0,0,0], [0,2]]
  15. symbols = "IVXLCDMↁↂ"
  16. r( n, s ) | n < 10 = map (\x->symbols!!(x+2*s)) (digitPattern!!n)
  17. | n >= 10 = r( div n 10, s+1) ++ r( mod n 10, s)
  18. in r(n,0)
  19.  
  20. main = print(toRoman 3896 )
Success #stdin #stdout 0s 4596KB
stdin
Standard input is empty
stdout
"MMMDCCCXCVI"