我试图在Haskell中创建一个代码,当k为偶数时,执行n ^ k =(n * n)^(k / 2),而n ^ k = n *(n ^(k-1) )如果k为奇数。 我做错了,但我不知道如何解决。
power2 :: Integer -> Integer -> Integer
power2 n 0 = 1
power2 n k
| k < 0 = error "negative argument"
| k `mod` 2 == 0 = even -- Am I supposed to write = even here?
| otherwise = odd
if k even = (n 2) ( div k 2) -- (n^2)^(k/2) ???
if k odd = n * (n) (k-1)) -- Is this n^(k-1) ???
答案 0 :(得分:5)
even
和odd
是Haskell中的函数,您可以在警戒条件内直接使用它们来测试数字是否为偶数/奇数。
以下是一种选择:
power2 :: Integer -> Integer -> Integer
power2 n 0 = 1
power2 n k
| k < 0 = error "negative argument"
| even k = power2 (n * n) (div k 2)
| odd k = n * ( power2 n (k-1) )
http://zvon.org/other/haskell/Outputprelude/odd_f.html http://zvon.org/other/haskell/Outputprelude/even_f.html
编辑:
当然,您可以编写自己的偶/奇函数版本,并将其用作替代版本。
示例:
myEven :: Integer -> Bool
myEven n = n `mod` 2 == 0
myOdd :: Integer -> Bool
myOdd n = n `mod` 2 == 1
power2 :: Integer -> Integer -> Integer
power2 n 0 = 1
power2 n k
| k < 0 = error "negative argument"
| myEven k = power2 (n * n) (div k 2)
| myOdd k = n * ( power2 n (k-1) )