You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中生成[x^0,x^1,x^2,x^3…]形式的无限列表?

Generating Infinite Power Sequences in Haskell

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
  • 1 is our starting point (that's x⁰)
  • (*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 x multiplied by x—so the next element is 1*x = x¹, then x*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 x creates an infinite list [x,x,x,...]
  • scanl (*) 1 starts with 1 and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:37:32