Reputation: 29
I was trying to half the even numbers in the list
halfEvens :: [Int] -> [Int]
halfEvens xs = [x `div` 2 | x -> xs, even x]
the error is error: parse error on input ‘->’
what does this mean and how to fix it? thanks
Upvotes: 0
Views: 1309
Reputation: 531
It has to do with your application of ->, basically -> is an infix type operator also known as the function arrow(function builder), who's purpose is to apply the arguments on the left to the right so
from -> to
but list comprehension works with <- which takes an IO action and binds it to the left argument so to <- from
, a small fix to your function:
halfEvens :: [Int] -> [Int]
halfEvens xs = [x `div` 2 | x <- xs, even x]
[Edit: Ignore anything else from here] =========================================================================
But if what you're trying is to divide all even numbers by 2 then you are doing it wrong, as this function would return only even numbers, while discarding all others.
halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) = if even x then x `div` 2 : halfEvens else x : halfEvens
Would be the correct way to do it, @AlexJ136 answer is also straight to the point, which seems much more efficient than mine, so I would go for it.
Upvotes: 0
Reputation: 1282
If you want to keep the odd numbers in the list:
halfEvens :: [Int] -> [Int]
halfEvens = map (\x -> if (x `mod` 2) == 0 then x `div` 2 else x)
Upvotes: 2
Reputation: 5405
halfEvens :: [Int] -> [Int]
halfEvens xs = [x `div` 2 | x <- xs, even x]
x <- xs
is read as x
is drawn from xs
.
Upvotes: 1