繁体   English   中英

Doc数据值构造函数Char和Text之间的区别

[英]Difference between Doc data value constructor Char and Text

我正在阅读Real World Haskell,第5章(编写JSON渲染器)。

data JValue = JString String
            | JNumber Double
            | JBool   Bool
            | JNull   
            ... 

data Doc = Empty
         | Char Char
         | Text String  
         | Concat Doc Doc
         ....  

我无法理解Char和Text(文档值构造函数)之间的区别。

renderJValue :: JValue -> Doc
renderJValue (JNumber n)        = Text $ show n
renderJValue (JBool   b)        = Text $ show b
renderJValue JNull              = Text "null"
renderJValue (JString (a:b:[])) = render a `Concat` render b 
    where render c = if isEscapeChar(c) 
                         then Text (c : [])
                         else Char c 


renderJValue $ JNumber 3                 
    = Text "3"
renderJValue $ JNull                     
    = Text "null"
renderJValue $ JString ("null")          
    = Char 'n' `Concat` Char 'u' `Concat` Char 'l' `Concat` Char 'l'
renderJValue $ JString ('a' : '\n' : []) 
    = Char 'a' `Concat` Text "\n"

区分字符和文本的优点是什么?

Text采用String参数。 Char采用单个Char值。 根据定义:

data Doc = Empty
         | Char Char
         | Text String
         | Line
         | Concat Doc Doc
         | Union Doc Doc
           deriving (Show,Eq)

您的示例似乎出现类型错误,因为您要在最后一行将“ \\ n”传递给Text。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM