Haskell幂函数实现问题:生成≤max的幂时结果数量不足
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

