我定義了一個接收資料型別和串列的函式。
getAux :: (Ord a) => SparseArray a -> [Bool] -> (Value a)
getAux (Node x left right) index
| length(index) == 0 = x
| head(index) == False = getAux (left) (tail(index))
| head(index) == True = getAux (right) (tail(index))
我遍歷這個傳遞索引尾部的函式 有 3 種可能的回傳: 如果串列的長度小于或等于 1,則回傳 x(存盤在節點中的值)如果不是,則檢查索引的頭部和它使用索引的尾部呼叫 getAux。
當我呼叫 getAux 時,我嘗試通過在索引末尾添加一個額外的元素來解決這個問題。而不是比較索引的長度是否等于 0 我將它與 1 進行比較。
當我呼叫該函式時,我有:
getAux (Nodo x iz de) (num2bin(index) [True])
新的 getAux 是:
getAux :: (Ord a) => SparseArray a -> [Bool] -> (Value a)
getAux (Node x left right) index
| length(index) == 1 = x
| head(index) == False = getAux (left) (tail(index))
| head(index) == True = getAux (right) (tail(index))
在這兩種情況下,我都會收到一個錯誤,表明我不能做空串列的頭部
uj5u.com熱心網友回復:
你用 呼叫它tail index,因此最終你到達空串列,因此這解釋了為什么后者,如果length index == 1失敗,它將嘗試訪問head index并因此出錯。
但是 usinglength不是一個好主意,因為它在O(n)中運行,串列的長度為n,通常在串列上執行模式匹配比使用headand更好tail,因為這樣可以保證串列具有head和tail。
因此,您可以將其實作為:
getAux :: SparseArray a -> [Bool] -> Value a
getAux (Node x _ _) [] = x
getAux (Node _ left right) (x:xs)
| x = getAux right xs
| otherwise = getAux left xs
通過為編譯器啟用[Haskell-docs],它會警告您該函式未涵蓋的模式。例如,如果您有一個額外的資料建構式,那么這些情況(還)不包括在內。-Wincomplete-patterns SparseArray
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/462866.html
上一篇:通過網路發送大型內容
