如何在Haskell中生成[x^0,x^1,x^2,x^3…]形式的无限列表?
Absolutely! Haskell's lazy evaluation is perfect for creating infinite sequences like [x⁰, x¹, x², x³, ...]—no need to predefine a length, since elements are generated on-demand. Here are a few clean, idiomatic ways to do this:
1. Using iterate (Most Concise)
The iterate function is made for exactly this kind of repeated transformation. It takes a function and a starting value, then generates an infinite list by applying the function over and over:
powers :: Num a => a -> [a] powers x = iterate (*x) 1
1is our starting point (that'sx⁰)(*x)is the function we apply repeatedly to get the next power- Example usage:
take 5 $ powers 2 -- Returns [1,2,4,8,16] take 3 $ powers 5 -- Returns [1,5,25]
2. Recursive Definition (Explicit and Intuitive)
If you prefer to spell out the logic yourself, a recursive list definition works great too. Lean on Haskell's laziness to avoid infinite loops:
powers :: Num a => a -> [a] powers x = 1 : map (*x) (powers x)
- The list starts with
1(x⁰) - The rest of the list is every element of
powers xmultiplied byx—so the next element is1*x = x¹, thenx*x = x², and so on - Example:
take 6 $ powers 2 -- Returns [1,2,4,8,16,32]
3. Using scanl (Alternative Approach)
You can also use scanl to accumulate the product as you go, paired with repeat to generate an infinite list of x values:
powers :: Num a => a -> [a] powers x = scanl (*) 1 (repeat x)
repeat xcreates an infinite list[x,x,x,...]scanl (*) 1starts with1and multiplies by each element of the repeated list in turn, building up the powers- Example:
take 4 $ powers 3 -- Returns [1,3,9,27]
Important Note
All these produce infinite lists, so you'll need to use functions like take, takeWhile, or drop to get a finite subset of elements—otherwise, GHCi will keep printing forever!
内容的提问来源于stack exchange,提问作者ishak lahlouh

