我剛開始學習 Haskell,在撰寫基本函式時遇到了問題。
這個函式應該告訴我陣列中有多少元素前一個元素比當前元素大。這是代碼:
countIncreases :: (Ord a, Num b) => [a] -> b -> b
countIncreases [x] c = c
countIncreases (x:y:r) c
| y > x = countIncreases (y:r) (c 1)
| otherwise = countIncreases (y:r) c
我嘗試用
countIncreases [1,2] 0
我粘貼了所有這些代碼,ghci但得到了錯誤
Non-exhaustive patterns in function countIncreases
但是,我認為該案例所需的所有模式都匹配:
- 1 ITER: ,,和。所以我們進入第一個分支并呼叫
x = 1y = 2r = []c = 02 > 1countIncreases (2:[]) (0 1) - 第二次迭代:
c = 1所以回傳1
我究竟做錯了什么?
uj5u.com熱心網友回復:
如果你運行你的函式,它不會產生錯誤,但是如果你編譯你打開的代碼-Wincomplete-patterns,并將警告視為錯誤(-Werror),它會出錯。
發生這種情況的原因是您無法使用空串列運行此函式。事實上,如果你用一個空串列呼叫它,[x]和(x:y:r)模式都會失敗。
如果您計算增加專案的數量,那么對于一個空串列,沒有這樣的元素,因此您可以通過以下方式實作:
countIncreases :: (Ord a, Num b) => [a] -> b -> b
countIncreases [] c = c
countIncreases [_] c = c
countIncreases (x:r@(y:_)) c
| y > x = countIncreases r (c 1)
| otherwise = countIncreases r c
uj5u.com熱心網友回復:
您忘記考慮空串列 ( []) 的情況:
countIncreases :: (Ord a, Num b) => [a] -> b -> b
countIncreases [x] c = c
countIncreases (x:y:r) c
| y > x = countIncreases (y:r) (c 1)
| otherwise = countIncreases (y:r) c
countIncreases [] c = c -- here!
但是,如果您認為永遠不應該這樣呼叫該函式,則可以拋出錯誤:
countIncreases [] _ = error "countIncrease on empty list!"
另一方面,我無法在您的測驗中重現該錯誤。
uj5u.com熱心網友回復:
謝謝你們回答我的問題。原來問題的根源是不同的。關鍵是我ghci逐行使用和插入多載,認為每一行都會給函式定義增加一個多載。結果是每一行我都覆寫了以前的輸入。所以記憶中總是只有最后一個存在。
從這個問題中,我學會了如何進行多行輸入,ghci并遵循我的功能正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416357.html
標籤:
