Reputation: 225
This is probably a fairly obvious question, but I just can't figure it out.
I am trying to write a function that squares the even numbers in a list. When I try to run it, I am getting an error about my use of the even function. How can I fix this?
module SquareEvens where
squareEvens :: [Integer] -> [Integer]
squareEvens n = [ns * ns | ns <- n, even n]
Upvotes: 4
Views: 5383
Reputation: 54574
As you can see, it's easy to get variable names wrong. So why not do it without?
squareEvens = map (^2) . filter even
I think this is clearer than the comprehension. You can read it from right to left: Keep only the even numbers, then square them.
Upvotes: 7
Reputation: 47042
The code works fine if you change even n
to even ns
:
squareEvens n = [ns * ns | ns <- n, even ns]
But note that the convention is to use the plural to name the list and the singular to name an element from that list. So swap n
and ns
to follow idiomatic Haskell usage:
squareEvens ns = [n * n | n <- ns, even n]
Upvotes: 12