受到罗马人、红宝石和 D 的启发,我想看看是否可以在 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
和:
{-# LANGUAGE TemplateHaskell #-}
import Romans
main = print $ $(roman "CCLXXXI")
首先,由于我是 Template Haskell 的新手,我想知道我是否做对了。实际计算发生在编译时,对吗?
其次,如何改进语法?
而不是$(roman "CCLXXXI")
我想要类似的东西roman "CCLXXXI"
,甚至更好的东西。到目前为止,我未能改进语法。