计算 Haskell 中自然数的指数
Calculate the exponential of Natural Numbers in Haskell
data Nat = Zero | Succ Nat
在Haskell中,使用声明,如何计算自然数n
和m
的幂,n^m
?
exponential :: Nat -> Nat
你可以通过先实现加法和乘法来制作它:
plus :: Nat -> Nat -> Nat
plus n Zero = n -- n + 0 = n
plus n (Succ m) = Succ (plus n m) -- n + (m + 1) = 1 + (n + m)
mult :: Nat -> Nat -> Nat
mult n Zero = Zero -- n * 0 = 0
mult n (Succ m) = plus n (mult n m) -- n * (m + 1) = n + n * m
expo :: Nat -> Nat -> Nat
expo n Zero = Succ Zero -- n^0 = 1
expo n (Succ m) = mult n (expo n m) -- n^(m + 1) = n * n^m
请注意,您描述的求幂类型应该是 Nat -> Nat -> Nat
,而不是 Nat -> Nat
。
data Nat = Zero | Succ Nat
在Haskell中,使用声明,如何计算自然数n
和m
的幂,n^m
?
exponential :: Nat -> Nat
你可以通过先实现加法和乘法来制作它:
plus :: Nat -> Nat -> Nat
plus n Zero = n -- n + 0 = n
plus n (Succ m) = Succ (plus n m) -- n + (m + 1) = 1 + (n + m)
mult :: Nat -> Nat -> Nat
mult n Zero = Zero -- n * 0 = 0
mult n (Succ m) = plus n (mult n m) -- n * (m + 1) = n + n * m
expo :: Nat -> Nat -> Nat
expo n Zero = Succ Zero -- n^0 = 1
expo n (Succ m) = mult n (expo n m) -- n^(m + 1) = n * n^m
请注意,您描述的求幂类型应该是 Nat -> Nat -> Nat
,而不是 Nat -> Nat
。