SmackMore
SmackMore

Reputation: 61

How to generate an infinite list in Haskell based on two inputs?

I need to generate an infinite list based on two inputs.

gen :: Int -> Int -> [Int]
gen x y

Every element needs to be (x*y) and x is incremented by y each iteration and the original x must be in the list too. So

gen 2 4

would result in

[2,8,24,40,..]

All of my attempts end up going forever (I use the call "take 4 (gen 2 4)" by in ghci the way) so I'm not sure how to proceed. Infinite lists just give me a lot of trouble. I'm trying to do this through do-notation and the list monad. Any help in the right direction would be much appreciated.

EDIT

This was my last attempt which didnt work. I'm learning Haskell through my friend and he gave me this problem to learn do notation for the list monad.

gen :: Int -> Int -> [Int]
gen x y = 
 do 
  a <- [x..]
  guard $ mod a (x*y) == 0
  let x = x+y
  return a

Upvotes: 3

Views: 1613

Answers (2)

fycth
fycth

Reputation: 3489

gen :: Int -> Int -> [Int]
gen x y = x : l
  where l = fmap (\m -> y * (2 + m * y)) [0..]

testing:

take 5 $ gen 2 4 [2,8,24,40,56]

Upvotes: 0

Alex
Alex

Reputation: 480

I think you could create a List comprehension.

ghci> [2]++[(4*i+2)*4|i<-[0..]]

You can use this in your function. You can change variable x instead of number "2" and your "y" instead of the number "4". Try it.

Finally, I have made a concatenation (++) between the List Comprehension and a list with [2] (the variable x).

Upvotes: 1

Related Questions