简体   繁体   English

Haskell 列表理解:显示偶数和双奇数元素

[英]Haskell List comprehension: show even and double odd elements

I've been working on an assignment and I just can't get it to work.我一直在做一项任务,但我无法让它工作。

I should write a function that takes a list of numbers and gives back a list that shows even numbers but doubles all odd numbers.我应该写一个 function ,它接受一个数字列表并返回一个显示偶数但将所有奇数加倍的列表。 (Basically the same list but with doubled odds). (基本上相同的列表,但赔率翻倍)。

doubleOdd :: [Integer] -> [Integer]
doubleOdd [] = []
doubleOdd a = [x*2 | x <- a, odd x]

My problems are:我的问题是:

  1. I'm only allowed to use +, -, *, /, ==, /=, sum, mod, elem, maximum, odd, even我只能使用 +、-、*、/、==、/=、sum、mod、elem、maximum、odd、even
  2. I don't know how I get different conditions for the same value to work (like if x is even = x and in the same List Comprehension have: if x is odd = x*2)我不知道如何获得相同值的不同条件(例如,如果 x 是偶数 = x 并且在同一个列表理解中有:如果 x 是奇数 = x*2)

So far I only got to print the even or the odd numbers, but never both.....到目前为止,我只需要打印偶数或奇数,但永远不会同时打印......

I hope someone can help me.我希望有一个人可以帮助我。

In the recursive case treat both possible cases, the case of odds and the case of evens, with the two mutually exclusive tests:在递归情况下,使用两个相互排斥的测试来处理两种可能的情况,即赔率情况和偶数情况:

doubleOdd a = [ .... | x <- a, y <- ([x*2 | .... x] ++ [x | .... x]) ]

Since the two tests are mutually exclusive, there will be only one result.由于这两个测试是互斥的,所以只会有一个结果。

You either must use ++ , or the if...then...else .您要么必须使用++ ,要么必须使用if...then...else I don't see a way to do this without one or the other.如果没有一个或另一个,我看不出有办法做到这一点。

Or maybe it can be done with some arithmetic trick but then it'd be a math question, not a Haskell question.或者也许它可以用一些算术技巧来完成,但它会是一个数学问题,而不是 Haskell 问题。

In case you are looking for a math-trick version:如果您正在寻找数学技巧版本:

> take 10 $ [ x + (x `mod` 2) * x | x <- [1..] ]
[2,2,6,4,10,6,14,8,18,10]

(you can do lot's of cheating like this with mod ) (你可以用mod做很多这样的作弊)

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

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