简体   繁体   English

你如何使用两个数字在Haskell中列出一个列表?

[英]How do you make a list in Haskell using two numbers?

Here is my problem: Declare type and define a function that takes two numbers m and n as input and returns a list containing the doubled values of all odd integers between m and n. 这是我的问题:声明类型并定义一个函数,它接受两个数字m和n作为输入,并返回一个包含m和n之间所有奇数整数的加倍值的列表。 For instance, fun 2 11 would return [6, 10, 14, 18, 22]. 例如,乐趣2 11将返回[6,10,14,18,22]。

I don't know how I can take the two number 2 and 11 and make it into a list [2..11]. 我不知道我怎么能拿出2号和11号这两个并将它列入一个列表[2..11]。 Does anyone know how to do this? 有谁知道如何做到这一点?

Use sequence generation (range syntax): 使用序列生成(范围语法):

Prelude> [2 .. 11]
[2,3,4,5,6,7,8,9,10,11]

Works for symbolic values, too: 也适用于符号值:

Prelude> let [m,n] = [2,11]
Prelude> [m .. n]
[2,3,4,5,6,7,8,9,10,11]

Didn't work with Haskell for almost two years, so correct me if I'm wrong and it doesn't work: 几乎两年没用Haskell了,所以如果我错了就纠正我,它不起作用:

getDoubledOdd :: Int -> Int -> [Int]
getDoubledOdd m n = map (2*) $ filter odd [m..n]

A combination of list comprehension and range would be the most standard way to do it. 列表理解和范围的组合将是最标准的方法。

[ 2*x | x <- [2..11], odd x ]

The code basically says "let x loop from 2 to 11 (x <- [2..11]), and if x is odd (odd x), put 2*x into the list that will be returned". 代码基本上是说“让x循环从2到11(x < - [2..11]),如果x是奇数(奇数x),则将2 * x放入将返回的列表中”。

Hope that explains. 希望解释一下。

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

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