[英]Haskell function to return all powers of a number until a given maximum
我正在創建一個函數,它返回n的所有小於或等於max的冪。 例如: powers 2 5
- > [1,2,4]。
myPowers n = n : map (* n) (myPowers n)
powers :: Int -> Int -> [Int]
powers n max = takeWhile (< max) (myPowers n)
目前, powers
的回報太少了。 例如: powers 2 6
應返回3個數字,但返回2個數字。
問題是你的myPowers
函數以n
開頭,而不是1
。 例如:
Prelude> take 10 $ myPowers 2
[2,4,8,16,32,64,128,256,512,1024]
我們可以解決這個問題:
myPowers n = 1 : map (* n) (myPowers n)
請注意,您可以使用iterate :: (a -> a) -> a -> [a]
使計算效率更高,因此您可以將其定義為:
myPowers n = iterate (n*) 1
如果要允許等於邊界的冪,則應檢查<=
的邊界:
powers n max = takeWhile (<= max) (myPowers n)
然后我們獲得樣本輸出,如:
Prelude> powers 2 5
[1,2,4]
Prelude> powers 2 6
[1,2,4]
Prelude> powers 2 10
[1,2,4,8]
Prelude> powers 3 10
[1,3,9]
Prelude> powers 3 30
[1,3,9,27]
Prelude> powers 5 30
[1,5,25]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.