Motivated by Romans, rubies and the D, I wanted to see if the same could be done in Haskell.
module Romans where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Data.Text
num :: String -> String
num s = rep $ pack s
where
r1 s1 = replace (pack "IV") (pack "IIII") s1
r2 s2 = replace (pack "IX") (pack "VIIII") s2
r3 s3 = replace (pack "XL") (pack "XXXX") s3
r4 s4 = replace (pack "XC") (pack "LXXXX") s4
rep = unpack . r4 . r3 . r2 . r1
value :: String -> Int
value s = cnt $ pack s
where
c1 s1 = (count (pack "I") s1) * 1
c2 s2 = (count (pack "V") s2) * 5
c3 s3 = (count (pack "X") s3) * 10
c4 s4 = (count (pack "L") s4) * 50
c5 s5 = (count (pack "C") s5) * 100
cnt t = c5 t + c4 t + c3 t + c2 t + c1 t
roman :: String -> ExpQ
roman s = return $ LitE (IntegerL (compute s))
where
compute s = fromIntegral $ value $ num s
and:
{-# LANGUAGE TemplateHaskell #-}
import Romans
main = print $ $(roman "CCLXXXI")
First, as I am new to Template Haskell, I would like to know if I've got it right. The actual computation happens at compile time, correct?
and second, how do I improve the syntax?
Instead of $(roman "CCLXXXI")
I would like something like roman "CCLXXXI"
, or even something better. So far I've failed to improve the syntax.