简体   繁体   中英

divide the even number in the list

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

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)
halfEvens :: [Int] -> [Int]
halfEvens xs = [x `div` 2 | x <- xs, even x]

x <- xs is read as x is drawn from xs .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM