Haskell编程中有折叠功能的代码。
map' ::(a->b)->[a]->[b]
map' f xs=foldr(\x acc ->f x:acc)[] xs
输入:
map' (+3) [1,2,3]
输出:
[4,5,6]
由于使用了foldr函数,它从右侧获取了元素,我想从左侧获取该元素并追加到列表中,并且我想要一个输出[6,5,4]。我通过foldl函数完成了它,但是它给出了错误。
ERROR: Couldn't match expected type `a' with actual type `[b]'
`a' is a rigid type variable bound by
the type signature for map' :: (a -> b) -> [a] -> [b]
at doubleme.hs:1:8
In the first argument of `f', namely `x'
In the first argument of `(:)', namely `f x'
In the expression: f x : acc
将函数签名更改为map' ::(a->b)->[a]->[b]
。
该map
操作基本上采用一个函数,该函数将类型为“ a”的元素转换为类型为“ b”的元素,并将其列表转换为类型“ a”的元素,以使用转换函数生成类型为“ b”的元素列表。您的函数签名包含另一种类型“ c”与此相反,因为不能隐式假定“ b”和“ c”是同一类型。
接下来,要使用foldl
,您必须反转输入参数的顺序,如下所示:
map' :: (a->b)->[a]->[b]
map' f xs = foldl (\acc x ->f x:acc) [] xs
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句