I'm receiving an error and don't know why.
mapo :: ((Float, Float) -> Float) -> [(Float, Float)] -> [Float]
mapo f [] = []
mapo f (x:y) = f x : mapo f y
Compiles ok.
*Main> mapo + [(1,2)]
Couldn't match type `(Float, Float) -> (Float, Float)' with `Float'
Expected type: (Float, Float) -> Float
Actual type: (Float, Float) -> (Float, Float) -> (Float, Float)
In the first argument of `mapo', namely `(+)'
In the expression: mapo (+) [(1, 2)]
In an equation for `it': it = mapo (+) [(1, 2)]
The purpose of this function is to receive an operator (let's say +
or -
), a list of pairs of numbers (Float
) and return the result of using that operator with each of the pairs of parameters of the list.
答案 0 :(得分:3)
Your problem is merely a syntactic error; When you want to partially apply an operator you need to wrap it in parentheses; So instead of
mapo + [(1,2)]
write
mapo (+) [(1,2)]
Otherwise it parses as adding mapo
to [(1,2)]
(i.e. (+) mapo [(1,2)]
which is clearly not what you want.
Next thing is getting the type right:
(+) :: Float -> Float -> Float
(in your case, its real type is more general) - but your function wants (Float,Float) -> Float
. These two types aren't equal, but they express pretty much the same thing so you can easily map between them with the curry :: ((a,b) -> c) -> a -> b -> c
and uncurry :: (a -> b -> c) -> (a,b) -> c
functions. In this case you need to pass uncurry (+)
to your mapo
function.
答案 1 :(得分:1)
(+)
does not have type (Float, Float) -> Float
, but uncurry (+)
does:
mapo (uncurry (+)) [(1,2)]
-> [3]
答案 2 :(得分:0)
*Main> mapo (\(a,b) -> a+b) [(1,2)]
[3.0]
Your problem is that mapo expects a function of the tuple (Float,Float)
but addition is a function on two Floats
, rather than a tuple.
*Main> :t (+)
(+) :: Num a => a -> a -> a
You can use mapo
as-is, as long as you remember to pass it a function which expects (Float,Float)
and returns Float
.