How do I create an infinite list in Haskell based on two inputs?

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

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

      

Each element should be (x * y) and x is incremented by y each iteration, and the original x should also be in the list. So

gen 2 4

      

will lead to

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

      

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

EDIT

This was my last try and didn't work. I am learning Haskell through a friend of mine and he gave me this problem to find out the 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

      

+3


source to share


2 answers


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 the variable x instead of the number "2" and "y" instead of the number "4". Try it.

Finally, I did a concatenation (++) between List List and list with [2] (variable x).

+1


source


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]

0


source







All Articles