简体   繁体   中英

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. For instance, fun 2 11 would return [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]. 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:

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".

Hope that explains.

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