gpt4 book ai didi

haskell - 在不使用列表的情况下内嵌长字符串

转载 作者:行者123 更新时间:2023-12-04 23:21:28 24 4
gpt4 key购买 nike

对于几个项目,我需要将长字符串嵌入到 Haskell 源代码中。

这样做的明显方法是unlines行列表。但是,阅读和维护它很麻烦。

cCode :: String
cCode = unlines [
"int main(int argc*, char** argv)",
" doStuff();",
"}"]

有没有什么方法可以在没有任何开销的情况下嵌入字符串(如上面显示的列表)甚至文件? TemplateHaskell/Quasi-quotation 是走这里的路吗?

注:这个问题以问答形式回答。因此,它没有显示任何研究工作。

最佳答案

可以使用 QuasiQuotation,如 in this blogpost written by me 所述。 .

第一步:创建一个包含所需功能的模块(我们称之为 StringEmbed.hs

module StringEmbed(embedStr, embedStrFile) where

import Language.Haskell.TH
import Language.Haskell.TH.Quote

embedStr :: QuasiQuoter
embedStr = QuasiQuoter { quoteExp = stringE,
quotePat = undefined,
quoteDec = undefined,
quoteType = undefined }

embedStrFile :: QuasiQuoter
embedStrFile = quoteFile embedStr

请注意,由于 TH 的特性,不可能将这些函数复制到您使用它们的模块中。

步骤 2a:在您的模块中,嵌入您的字符串:

{-# LANGUAGE QuasiQuotes #-}

import StringEmbed

cCode :: String
cCode = [embedStr|
int main(int argc, char** argv) {
doStuff();
}
|]

请注意,您只需添加 QuasiQuotes LANGUAGE语用。 TemplateHaskell此技术不需要。

因为 QuasiQuotes 是使用 |] 分隔的。 ,您不能在准引号字符串中的任何位置使用该字符序列。

步骤 2b:您可以轻松地嵌入文件。假设文件 code.c包含您要嵌入的字符串。

{-# LANGUAGE QuasiQuotes #-}

import StringEmbed

cFooter :: String
cFooter = [embedStrFile|code.c|]

或者 您可以使用许多 haskell 库之一,而不是 StringEmbed.hs ,例如 heredoc (感谢 Ørjan Johansen 的提示!)

{-# LANGUAGE QuasiQuotes #-}
import Text.Heredoc


cCode :: String
cCode = [here|
int main(int argc, char** argv) {
doStuff();
}
|]

关于haskell - 在不使用列表的情况下内嵌长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25148745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com