Reputation: 1437
I have the following code which halves each even number in a list:
halfEvens :: [Int] -> [Int]
halfEvens [xs]
| x `mod` 2 == 0 = x `div` 2
| otherwise = x
where x <- xs
And I get the following error:
parse error on input '<-'
I was careful so I respected the indentations...any other ideas what I'm doing wrong?
Upvotes: 1
Views: 863
Reputation: 33661
There are two main issues in your code:
where
block defines functions, so, you should use =
instead of <-
Instead of it I suggest you write separate function halfIfEven
:
Prelude> let halfIfEven x = if even x then x `div` 2 else x
Then define halfEvens
using map
:
Prelude> let halfEvens = map halfIfEven
Prelude> halfEvens [1..10]
[1,1,3,2,5,3,7,4,9,5]
But, of course, you could write this using pattern matching, although it is less readable:
halfIfEven :: Int -> Int
halfIfEven x | even x = x `div` 2
| otherwise = x
halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) = (halfIfEven x):(halfEvens xs)
Upvotes: 3