Diana
Diana

Reputation: 1437

Haskell- parse error on input

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

Answers (1)

awesoon
awesoon

Reputation: 33661

There are two main issues in your code:

  1. where block defines functions, so, you should use = instead of <-
  2. Your function accepts lists with exactly one element inside

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

Related Questions