为什么用这种方式使用foldr编写地图
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) []
Run Code Online (Sandbox Code Playgroud)
给出以下错误?
test.hs:2:13: error:
• Couldn't match expected type ‘[b]’ with actual type ‘t0 a -> [b]’
• Probable cause: ‘foldr’ is applied to too few arguments
In the expression: foldr (\ x acc -> f x : acc) []
In an equation for ‘map'’:
map' f xs = foldr (\ x acc -> f x : acc) []
• Relevant bindings include
xs :: [a] (bound at test.hs:2:8)
f :: a -> b (bound at test.hs:2:6)
map' :: (a -> b) -> [a] -> [b] (bound at test.hs:2:1)
|
2 | map' f xs = foldr (\x acc -> f x : acc) []
| ^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
你不用xs.你可以写:
map' f xs = foldr (\x acc -> f x : acc) [] xs
Run Code Online (Sandbox Code Playgroud)
要么
map' f = foldr (\x acc -> f x : acc) []
Run Code Online (Sandbox Code Playgroud)