fo-6ren">
gpt4 book ai didi

haskell - 如何在 Haskell 中将元组返回值转换为 "positional"参数?

转载 作者:行者123 更新时间:2023-12-02 15:47:01 24 4
gpt4 key购买 nike

我知道没有“位置”参数,因为所有函数都只接受一个变量并返回一个函数来对其余参数进行操作,但这就是我想要做的:

从我用来格式化列表的一些函数开始,其中包含前置项、分隔符和结束项。

Prelude> formatList start end sep xs = start ++ (intercalate . separator ( map show xs )) ++ end

工作原理如下:

Prelude Data.List> formatList "(" ")" "," [1..10]
"(1,2,3,4,5,6,7,8,9,10)"

很酷,同样的想法也可以用于 xml 标签:

Prelude Data.List> formatList "<meow>" "</meow>" "" [1..10]
"<meow>12345678910</meow>"

本着重用函数和简洁的精神,我们也可以通过创建一个函数来仅从单词“tag”生成打开和关闭,这样我们就不必键入 meow 标记的冗余部分。

Prelude Data.List> tagger tag item = "<" ++ tag ++ ">" ++ item ++ "</" ++ tag ++ ">"
Prelude Data.List> tagger "div" "contents"
"<div>contents</div>"

现在制作一些将返回开始和结束的标记制作器,我可以为 formatList 函数添加第二个参数:

Prelude Data.List> tagMaker tag = ("<" ++ tag ++ ">", "</" ++ tag ++ ">")

看起来不错:

Prelude Data.List> tagMaker "div"
("<div>","</div>")

现在就试试吧。实际行为:

Prelude Data.List> formatList (tagMaker "div") "" [1..10]

<interactive>:49:13: error:
• Couldn't match expected type ‘[Char]’
with actual type ‘([Char], [Char])’
• In the first argument of ‘formatList’, namely ‘(tagMaker "div")’
In the expression: formatList (tagMaker "div") "" [1 .. 10]
In an equation for ‘it’:
it = formatList (tagMaker "div") "" [1 .. 10]

期望的行为:

formatList (tagMaker "div") "" [1..10]
"<div>12345678910</div>

使 tagMaker 函数能够子代一个期望获取其第一个值,然后是其第二个值的函数的正确方法是什么?如果这完全不符合习惯用法,那么正确的习惯用法是什么?

最佳答案

usual trick对于命名参数似乎可能会感兴趣。

data Formatter = Formatter { start, end, sep :: String }

formatList :: Show a => [a] -> Formatter -> String
formatList xs fmt = start fmt ++ intercalate (sep fmt) (map show xs) ++ end fmt

with :: Formatter
with = Formatter "" "" ""

现在您原来的调用如下所示:

formatList [1..10] with { start = "(", end = ")", sep = "," }
formatList [1..10] with { start = "<meow>", end = "</meow>" }

你可以这样创建一个格式化工厂:

xmlTag :: String -> Formatter
xmlTag t = with { start = "<" ++ t ++ ">", end = "</" ++ t ++ ">" }

用法如下:

formatList [1..10] (xmlTag "div")               -- use the default separator
formatList [1..10] (xmlTag "div") { sep = "," } -- specify a separator

关于haskell - 如何在 Haskell 中将元组返回值转换为 "positional"参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54283012/

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