受Romans, rubies and the 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")
首先,我是新来的模板哈斯克尔,我想知道如果我是正确的。实际的计算在编译时发生,对吗?
第二,我该如何改进语法?
而不是$(roman "CCLXXXI")
我想要像roman "CCLXXXI"
,甚至更好的东西。到目前为止,我没有改进语法。
其实,唐·斯图尔特有一个很好的[博客文章(http://donsbot.wordpress.com/2010/03/01/evolving-faster-haskell-programs-now-with-llvm /)描述了如何使用适当的交换机的LLVM后端预编译没有模板扩展的Haskell 98代码。 – 2012-03-31 04:28:13