Haskell Even?

This is probably a pretty obvious question, but I just can't figure it out.

I am trying to write a function that squares even numbers in a list. When I try to start it, I get a message that I am using an even function. How can i fix this?

module SquareEvens where squareEvens :: [Integer] -> [Integer] squareEvens n = [ns * ns | ns <- n, even n] 
+4
source share
2 answers

The code works fine if you change even n to even ns :

 squareEvens n = [ns * ns | ns <- n, even ns] 

But keep in mind that the convention is to use the plural to name a list, and the only one to name an item from this list. Therefore, replace n and ns with the idiomatic use of Haskell:

 squareEvens ns = [n * n | n <- ns, even n] 
+11
source

As you can see, it is easy to get the wrong variable names. So why not do it without?

 squareEvens = map (^2) . filter even 

I think this is clearer than understanding. You can read it from right to left: store only even numbers and then square ones.

+7
source

All Articles