[英]Explanation of map functions (using foldr) in Haskell?
I'm trying to define the map function using foldr我正在尝试使用 foldr 定义 map function
I have found the two following solutions, however I'm not quite sure how they are working.我找到了以下两个解决方案,但是我不太确定它们是如何工作的。
map' :: (a -> b) -> [a] -> [b]
map' f = foldr ((:) . f) []
map'' :: (a -> b) -> [a] -> [b]
map'' f = foldr (\x xs -> f x : xs) []
I'm quite new to Haskell and foldr, so I'm struggling to understand what ((:). f)
in the first solution and what (\x xs -> fx: xs)
in the second solution do.我对 Haskell 和 foldr 很陌生,所以我很难理解第一个解决方案中的
((:). f)
和第二个解决方案中的(\x xs -> fx: xs)
做什么。
I also don't get how foldr is able handle the empty list case.我也不明白 foldr 如何处理空列表的情况。
It would be much appreciated if I could get a simple step by step explanation of this, in layman's terms.如果我能用外行的方式简单地一步一步地解释这一点,将不胜感激。
Both (\x xs -> fx: xs)
and (:). f
(\x xs -> fx: xs)
和(:). f
(:). f
mean the same thing. (:). f
意思相同。 They're both functions that take two arguments, apply f
to the first argument, and then cons that onto the second argument.它们都是采用两个 arguments 的函数,将
f
应用于第一个参数,然后将其应用于第二个参数。
So what does foldr
do when given an empty list?那么当给定一个空列表时,
foldr
会做什么呢? It simply returns the starting value, which in these examples is []
.它只是返回起始值,在这些示例中为
[]
。
Here is the implementation of foldr
from Hackage :这是来自Hackage的
foldr
的实现:
foldr k z = go
where
go [] = z
go (y:ys) = y `k` go ys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.