How do you use range in haskell with variable spacing between elements

I have the following code snippet, and I'm not sure where my errors are. The goal is to pass two values valand facand list the form [val1, val1*fac,val1*fac*fac...], but it does not 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 I get[2,6,18,18,18...]

+3
source share
3 answers

I feel that you are trying to translate the imperative algorithm directly into Haskell. The standard way to define such infinite lists is to use laziness and recursion:

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

If you want to use list comprehension:

gm val fac = [val * fac^i | i <- [1..]]
+5
source

I think you can do:

gm' val fac = iterate (*fac) val

Conclusion:

*Main> take 5 $ gm' 2 3
[2,6,18,54,162]

, , val, k, j.

+3

, , , . , , x val, val+1,...

  x    k        j                   x == val? x == val+1? element
--------------------------------------------------------- -------
val    val*fac  fac*k = val*val*fac True      False       val         (x)
val+1  val*fac  fac*k = val*val*fac False     True        val*fac     (k)
val+2  val*fac  fac*k = "           False     False       val*val*fac (j)
val+3  val*fac  fac*k = "           False     False       val*val*fac (j)
...

, , k j , val fac.

Haskell. :

[ 1, fac, fac*fac, fac*fac*fac, ...]

map (val*).

, :

1) (*fac). , :

f x = fac*x

:

[ 1, f 1, f (f 1), f (f (f 1)), ... ]

, iterate .

2) Note that the tail is a sequence of powers of a sequence of map (*fac)sequences. Therefore, you can write:

powers x = 1 : map (*x) (powers x)

This is essentially the same as (1), but sometimes it is easier to determine the relationship between the sequence and the tail.

+2
source

All Articles