我正在尝试编写一个类似的函数map,但它将类型函数(a, a) -> b作为其第一个参数.但是,我得到了错误
<interactive>:474:11: error:
Parse error in pattern: \ (x, y) -> f x y
Run Code Online (Sandbox Code Playgroud)
使用以下代码:
Prelude> :{
Prelude| mappairs :: ((a, a) -> b) -> [a] -> [b]
Prelude| mappairs (\(x,y) -> f x y) xs = foldr (\(x, y) acc -> (f x y : acc)) [] xs
Prelude| :}
Run Code Online (Sandbox Code Playgroud)
问题是什么?
模式:
\(x,y) -> f x yRun Code Online (Sandbox Code Playgroud)
在条款中:
mappairs (\(x,y) -> f x y) xs = foldr (\(x, y) acc -> (f x y : acc)) [] xsRun Code Online (Sandbox Code Playgroud)
确实无效,因为(->)它不是数据构造函数.
但是你可以zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]在这里使用:
mappairs :: ((a, a) -> b) -> [a] -> [b]
mappairs _ [] = []
mappairs f xa@(_:xs) = zipWith (curry f) xa xsRun Code Online (Sandbox Code Playgroud)
例如:
> mappairs (\(x,y) -> x+y) [1,4,2,5]
[5,6,7]
Run Code Online (Sandbox Code Playgroud)
但它看起来更像是" Haskell-ish "来省略元组,因此直接使用函数:
mappairs :: (a -> a -> b) -> [a] -> [b]
mappairs _ [] = []
mappairs f xa@(_:xs) = zipWith f xa xsRun Code Online (Sandbox Code Playgroud)