1

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.