Haskell/解決方案/遞迴
外觀
| 練習 |
|---|
|
factorial可以定義如下factorial 0 = 1 factorial n = n * factorial(n - 1)
- 輸入
factorial (-1)應該會顯示訊息*** Exception: stack overflow。這是因為根據定義,factorial (-1)是(-1) * factorial (-2),即(-1) * (-2) * factorial (-3)。這將永遠不會停止,因此函式將一直執行,直到它耗盡記憶體。 doubleFactorial可以定義如下
doubleFactorial 0 = 1
doubleFactorial 1 = 1
doubleFactorial n = n * doubleFactorial (n-2)
| 練習 |
|---|
|
1. 5 × 4
- 4 不等於 1,因此我們遞迴:計算 5 × 3
- 3 不等於 1,因此我們遞迴
- 2 不等於 1,因此我們遞迴
- 1 等於 1,因此我們返回 5
- 我們將當前數字 5 加到遞迴結果 5 中。我們得到 10
- 我們將當前數字 5 加到遞迴結果 10 中。我們得到 15
- 我們將當前數字 5 加到遞迴結果 15 中。我們得到 20。
2.
power x 0 = 1
power x y = x * power x (y-1)
3.
addition x 0 = x
addition x y = plusOne (addition x (y-1))
4.
log2 1 = 0
log2 n = 1 + log2 (n `div` 2) -- the "`" make div into infix notation
| 練習 |
|---|
|
為以下基於列表的函式給出遞迴定義。在每種情況下,考慮基本情況是什麼,然後考慮一般情況在比它小的所有事物方面會是什麼樣子。
|
1-3 的答案,在一個程式碼塊中
replicat 0 _ = []
replicat n thing = thing : replicat (n-1) thing
[] !! _ = error "Index too large" -- An empty list has no elements.
(x:_) !! 0 = x
(x:xs) !! n = xs !! (n-1)
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys
(x:xs) 不匹配空列表,因此你也可以有
zip (x:xs) (y:ys) = (x,y) : zip xs ys
zip _ _ = []
以下是累積的 length
length xs = go 0 xs
where
go acc [] = acc
go acc (_:xs) = go (acc + 1) xs