简体   繁体   English

在列表中除以偶数

[英]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 . x <- xs被读取,因为x 是从 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: 它与您的->的应用程序有关,基本上->是一个中缀类型运算符,也称为函数arrow(function builder),其目的是将左侧的参数应用于右侧,因此from -> to but列表comprehension与<-一起使用 ,这将执行IO操作并将其绑定到左参数,因此to <- from -from绑定到您的函数的一个小修正:

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. 但是,如果您尝试将所有偶数除以2,那么您做错了,因为此函数将仅返回偶数,而丢弃所有其他数。

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. 这将是正确的方法,@ AlexJ136答案也很明确,这似乎比我的要有效得多,所以我会去做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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