Reputation:
I'm trying to get the sum of all even numbers with a function in Haskell, but it doesn't seem to work.
This is how my code looks like:
sumEvenNumbers :: [Int] -> Int
sumEvenNumbers n = sum . even
Anyone has a solution to this? Thanks!
Upvotes: 0
Views: 2123
Reputation: 2167
The type of even
is even :: (Integral a) => a -> Bool
, meaning you give it a number and it tells you whether it is even or not. You are trying to apply this function to a list of numbers which doesn't make sense.
What you want instead is a function that gives you back a list of the numbers that are even. To accomplish that you want filter
which has the type filter :: (a -> Bool) -> [a] -> [a]
, and it will apply the function to the original list and give back only those things that evaluated to True.
Additionally, when you are going to define a function point-free style, you don't need to (actually, language does not allow you to) give arguments to the function, so the n
is unnecessary.
Upvotes: 4
Reputation:
You want sumEvenNumbers = sum . filter even
(note the absence of the argument on the left-hand side of the equation). even
doesn’t work on lists, but on single integers.
A more explicit equivalent is sumEvenNumbers xs = sum (filter even xs)
.
Upvotes: 6