【问题标题】:Haskell QuasiQuotes Text.RawString.QQ interpolationHaskell QuasiQuotes Text.RawString.QQ 插值
【发布时间】:2018-11-14 05:43:48
【问题描述】:
我怎样才能像这样插值:
{-# LANGUAGE QuasiQuotes #-}
import Text.RawString.QQ
myText :: Text -> Text
myText myVariable = [r|line one
line two
line tree
${ myVariable }
line five|]
myText' :: Text
myText' = myText "line four"
${ myVariable } 打印为文字,而不是插值,在这种情况下我可以做类似的插值吗?
【问题讨论】:
-
嗯,你期待什么?这正是r quasi-quoter 按原样复制文本而不进行任何转义等的重点。您将需要一个不同的 quasi-quoter 来获得这种行为。但这是一个 SO 问题的主题。你为什么没有just searched hackage呢? — FWIW,我不喜欢这种情况下的插值一词,也不喜欢技术本身。通常最好从块中构建这样的字符串,这可以通过fmt 很好地完成。
-
@leftaroundabout 我认为插值可能有用。有时您可以在其中只需要配置小部分的大量预定义文本。请参阅summoner 中的示例。 fmtpackage 当您需要使用一组预定义的运算符(尤其是日期)以自定义方式格式化小消息时非常有用。类似的东西:github.com/serokell/importify/blob/…
标签:
haskell
string-interpolation
quasiquotes
【解决方案1】:
准引用器r 不实现插值。它仅适用于原始字符串。你需要另一个准引用者。
完整代码:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Data.Text (Text)
import Text.RawString.QQ (r)
import NeatInterpolation (text)
rQuote :: Text -> Text
rQuote myVariable = [r|line one
line two
line tree
${ myVariable }
line five|]
neatQuote :: Text -> Text
neatQuote myVariable = [text|line one
line two
line tree
$myVariable
line five|]
rText, neatText :: Text
rText = rQuote "line four"
neatText = neatQuote "line four"
在ghci:
*Main> import Data.Text.IO as TIO
*Main TIO> TIO.putStrLn rText
line one
line two
line tree
${ myVariable }
line five
*Main TIO> TIO.putStrLn neatText
line one
line two
line tree
line four
line five
【解决方案2】:
我实现目标的唯一方法就是连接:
{-# LANGUAGE QuasiQuotes #-}
import Text.RawString.QQ
myText :: Text -> Text
myText myVariable = [r|line one
line two
line tree
|] <> myVariable <> [r|
line five|]
myText' :: Text
myText' = myText "line four"