我正在尝试编写一个类似于map
的函数,但该函数将(a, a) -> b
类型的函数作为其第一个参数。但是,出现错误
<interactive>:474:11: error:
Parse error in pattern: \ (x, y) -> f x y
具有以下代码:
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| :}
出什么问题了?
答案 0 :(得分:5)
模式:
\(x,y) -> f x y
在条款中:
mappairs (\(x,y) -> f x y) xs = foldr (\(x, y) acc -> (f x y : acc)) [] xs
确实无效,因为(->)
不是数据构造函数。
不过,您可以在此处使用zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
mappairs :: ((a, a) -> b) -> [a] -> [b]
mappairs _ [] = []
mappairs f xa@(_:xs) = zipWith (curry f) xa xs
例如:
> mappairs (\(x,y) -> x+y) [1,4,2,5]
[5,6,7]
但是省略元组看起来更像“ Haskell-ish ”,因此可以直接使用函数:
mappairs :: (a -> a -> b) -> [a] -> [b]
mappairs _ [] = []
mappairs f xa@(_:xs) = zipWith f xa xs