我在打印出Data.Text实例之前一直在打印出来进行调试,并认为只是使用Text.Printf进行打包.不幸的是,我不能使它工作:
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import Data.Text import Text.Printf --instance PrintfArg Text where -- toUPrintf = toUPrintf . unpack main :: IO () main = do let input :: Text = "abc" printf "Input: %s\n" input
错误:
src/Main.hs:12:3: No instance for (PrintfArg Text) arising from a use of `printf' Possible fix: add an instance declaration for (PrintfArg Text) In a stmt of a 'do' block: printf "Input: %s" input In the expression: do { let input :: Text = "abc"; printf "Input: %s" input } In an equation for `main': main = do { let input :: Text = ...; printf "Input: %s" input }
取消注释实例声明后:
src/Main.hs:7:7: `toUPrintf' is not a (visible) method of class `PrintfArg' src/Main.hs:7:19: Not in scope: `toUPrintf'
有任何想法吗?
EDITED
如所建议的,尝试TH,还是不行:
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} import Data.Text import Language.Haskell.TH import Text.Printf runQ [d| instance PrintfArg Text where toUPrintf = toUPrintf . unpack|] main :: IO () main = do let input :: Text = "abc" printf "Input: %s\n" input
错误:
src/Main.hs:9:40: 'toUPrintf' is not a (visible) method of class 'PrintfArg' src/Main.hs:9:52: Not in scope: 'toUPrintf'
帮帮我!令人惊奇的是,默认情况下,使用Data.Text的所有建议都没有开箱即用.
解决方法
我会看看
text-format软件包:它类似于Text.Printf,但专门为Data.Text.Lazy设计.
与Text.Printf相比,文本格式还有其他一些优点:
> Buildable
类被暴露,因此可以扩展以支持新的参数类型.
>它使用一个更简单的方法来修改,它避开了具有accessing the return value的Text.Printf中的问题.
它应该要快得多,原因有几个:
>它不会转换为低效的字符串表示形式;
>它不会构建中间数据类型,与Text.Printf中的UPrintf
不同;
>它使用double-conversion包来渲染Double和Float,比Prelude的方法大约是30 times faster.