作者:maggieting0334_990 | 来源:互联网 | 2022-11-20 16:55
我理解没有"位置"参数,因为所有函数只接受一个变量并返回一个函数来操作剩余的参数,但这就是我想要做的意思:
从一些函数开始,我用来格式化带有前置项,分隔符和结束项的列表.
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 "" "" "" [1..10]
"12345678910"
本着重用函数和简洁性的精神,让我们也做到这一点,我们不必通过创建一个函数来生成打开和关闭单词"tag",从而输入meow标记的冗余部分.
Prelude Data.List> tagger tag item = "<" ++ tag ++ ">" ++ item ++ "" ++ tag ++ ">"
Prelude Data.List> tagger "div" "contents"
"contents
"
所以现在制作一些标签制作器,它将返回一个开始和结束我可以为我的formatList函数创建第二个参数:
Prelude Data.List> tagMaker tag = ("<" ++ tag ++ ">", "" ++ tag ++ ">")
看起来不错:
Prelude Data.List> tagMaker "div"
("","
")
现在试试吧.实际行为:
Prelude Data.List> formatList (tagMaker "div") "" [1..10]
: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]
"12345678910
什么是使tagMaker函数能够为一个期望获取其第一个值,然后是第二个值的函数的子函数的正确方法是什么?如果这完全是非惯用的,那么正确的习惯用法是什么?
1> Daniel Wagne..:
命名参数的常用技巧似乎可能是有意义的.
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 = "", end = "" }
您可以这样制作格式化工厂:
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