jam*_*her 27 text haskell typeclass
大家都知道Show
.但是关于:
class ShowText a where
showText :: a -> Text
Run Code Online (Sandbox Code Playgroud)
我无处可寻.为什么?
Edw*_*ETT 15
直接创建Text的问题是在填写之前您仍然需要知道严格Text块的整体大小.您可以使用Builder方案并使用Data.Text.Lazy做得更好.Dan Doel在bytestring-show中执行此操作,但我不知道Text的等效项.
Col*_*ury 14
库文本显示现在存在并且正好解决了这个问题.
更新(2016年2月12日)
该show
所提供的功能基本-前奏库还直呈现文本:
show :: Show a => a -> Text
Run Code Online (Sandbox Code Playgroud)
basic-prelude
依赖性也比text-show
.如果您想使用basic-prelude
,请通过在源文件的顶部添加以下内容来节省编译难题:
{-# LANGUAGE NoImplicitPrelude #-}
Run Code Online (Sandbox Code Playgroud)
对于Int
值的特定情况,这里是将它们转换为严格Text
值而不Strings
在中间阶段使用的代码:
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Builder.Int (decimal)
showIntegral :: Integral a => a -> T.Text
showIntegral = toStrict. toLazyText . decimal
Run Code Online (Sandbox Code Playgroud)
模块Data.Text.Lazy.Builder.RealFloat
为浮点值提供类似的功能.
有了这些,我们可以定义一个我们自己的Show
类型类型:
import Data.Text
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText)
import Data.Text.Lazy.Builder.Int (decimal)
import Data.Text.Lazy.Builder.RealFloat (realFloat)
class ShowText a where
showText :: a -> Text
instance ShowText Int where
showText = toStrict . toLazyText . decimal
instance ShowText Float where
showText = toStrict . toLazyText . realFloat
Run Code Online (Sandbox Code Playgroud)
然后我们可以开始添加更多实例(例如,一个用于元组的实例).