Reputation: 95
I am struggling with trying to implement the foldr() function, the function I made in the code shown below, which is a function to multiply every element in an array by 2 but it gave me an error message(shown below too), and I don't quite know how to fix it. I am open to suggestions, so any tips or fixes will greatly help. Thanks Here is the source code
multwo ::[a] -> [a]
multwo = foldr(\x acc-> (2*x):acc)[]
Here is the error message
• No instance for (Num a) arising from a use of ‘*’
Possible fix:
add (Num a) to the context of
the type signature for:
multwo :: forall a. [a] -> [a]
• In the first argument of ‘(:)’, namely ‘(2 * x)’
In the expression: (2 * x) : acc
In the first argument of ‘foldr’, namely
‘(\ x acc -> (2 * x) : acc)’
|
9 | multwo = foldr(\x acc-> (2*x):acc)[]
| ^^^
Upvotes: 2
Views: 71
Reputation: 477190
Your multwo
function aims to multiply all elements with two, but that is only possible if this is a list of numbers. Haskell has the Num
typeclass to group all number types. You thus should add a type constraint to the signature:
multwo :: Num a => [a] -> [a]
multwo = foldr (\x acc-> (2*x) : acc) []
You can shorten the folding function further to:
\x -> (2*x :)
and further to:
(:) . (2 *)
so a shorter implementation looks like:
multwo :: Num a => [a] -> [a]
multwo = foldr ((:) . (2*)) []
Upvotes: 1