'地图'高阶 Haskell 函数
例如,我有一个列表:
["Hello", "Goodbye"]
并且我想在列表上使用map
;
我之前已经成功使用过map
:
f = ("example" ++)
所以那么:
map f ["Hello", "Goodbye"]
会制作列表:
["exampleHello", "exampleGoodbye"]
但是我如何在函数f
中使用列表项?
例如,如果我想重复列表元素,那么
["Hello", "Goodbye"]
将变为
["HelloHello", "GoodbyeGoodbye"]
How can I do that with map
和函数f
(以及++
)?
I have a list, for example:
["Hello", "Goodbye"]
and I want to use map
on the list;
I've successfully used map
before:
f = ("example" ++)
so then:
map f ["Hello", "Goodbye"]
Would make the list:
["exampleHello", "exampleGoodbye"]
but how can I use the list items in the function f
?
For example, if I wanted to repeat the list element, so
["Hello", "Goodbye"]
would become
["HelloHello", "GoodbyeGoodbye"]
How can I do that with map
and a function f
(and ++
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以
So
f
的结果定义为
fx = (x++x)
。Doing
results in
So
f
could be defined asf x = (x++x)
.您可能想使用 lambda 函数来完成此类事情。您想要查看列表中的每个项目,然后将其替换为自身的副本。复制字符串很容易:
\str -> str ++ str
,现在您只需将该函数映射到列表上:You'd probably want to use a lambda function for this kind of thing. You want to look at each item of the list, and then replace it with itself duplicated. Duplicating a string is easy:
\str -> str ++ str
, and now you just need to map that function over the list: