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

Haskell幂函数实现问题:生成≤max的幂时结果数量不足

Fixing Your Power Sequence Function

Let's break down the issues with your current code and fix them step by step:

1. Missing the 0th Power (1)

Your myPowers function starts generating from n^1 (e.g., myPowers 2 gives [2,4,8,...]), but your example expects 1 (which is n^0) as the first element. That's why your output is missing the initial element that should be included.

2. Filtering Out Elements Equal to max

You're using takeWhile (< max), which stops as soon as it hits an element greater than or equal to max. But your requirement is to include elements that are less than or equal to max, so the condition needs to be adjusted to match your needs.

Corrected Code

Here's the fixed version that addresses both issues:

-- Now starts with 1 (n^0), then generates n^1, n^2, etc.
myPowers n = 1 : map (* n) (myPowers n)

-- Use <= max to include elements equal to the maximum value
powers :: Int -> Int -> [Int]
powers n max = takeWhile (<= max) (myPowers n)

Testing It Out

  • powers 2 5 → [1,2,4] (matches your example perfectly)
  • powers 2 6 → [1,2,4] (3 elements, as you expected)
  • powers 3 10 → [1,3,9] (correctly includes 9 which is ≤10)

Handling Edge Case: n=1

If you pass n=1, the original myPowers would generate an infinite list of 1s. To avoid that (since 1^k is always 1), you can add a special case to make the behavior more intuitive:

myPowers 1 = [1]  -- Only return 1 once, since all powers of 1 are identical
myPowers n = 1 : map (* n) (myPowers n)

Now powers 1 5 returns [1] instead of an infinite list, which aligns with real-world expectations.

内容的提问来源于stack exchange,提问作者Aelin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:36:01