Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use a range in haskell with a variable distance between elements

I have the following code snippet started, and i'm not sure where my error(s) are. The goal is to pass in two values, val and fac and output a list of the form [val1, val1*fac,val1*fac*fac...] but it doesn't work.

 gm :: Int -> Int -> [Int]
 gm val fac = let j=0 in
[ if (x==val) then x else if (x==(val+1)) then k else j 
| x <- [val..], let k = val*fac, let j = fac*k]

For example if I called gm 2 3 I should get the result [2,6,18,54,162...] but what I get is [2,6,18,18,18...]

like image 322
cHam Avatar asked Jan 18 '26 23:01

cHam


1 Answers

I feel like you're trying to translate an imperative algorithm directly to Haskell. The standard way of defining such infinite lists is by using laziness and recursion:

gm val fac = val : gm (val * fac) fac

If you want to use a list comprehension:

gm val fac = [val * fac^i | i <- [1..]]
like image 124
Daniel Avatar answered Jan 20 '26 15:01

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!