簡體   English   中英

函數 buildTree' Haskell 中的非窮盡模式

[英]Non-exhaustive patterns in function buildTree' Haskell

我使用返回元組的函數。 但是當我嘗試運行該函數時,它給了我一個例外:函數中的非窮盡模式。

buildTree' :: String -> Tree  -> (String,Tree)
buildTree' (x:xs)  currenttree 
|null (x:xs) = ("empty", currenttree)
|isDigit x && ( take 1  xs == ['+'] ||  take 1 xs == ['-'])= buildTree' xs (Node [x] Empty Empty)
|isDigit x = buildTree' newstring1 (snd (buildrecursion (getminiexpr(x:xs)) Empty))
|elem x "+-" = buildTree' newstring (buildTree2 currenttree newtree [x])
    where newtree = (snd (buildrecursion (getminiexpr xs) Empty))
          newstring = drop (length(getminiexpr xs)) xs
          newstring1 = drop (length(getminiexpr (x:xs))) (x:xs)


getminiexpr :: String -> String 
getminiexpr input = takeWhile ( \y -> y /= '+' && y /= '-') input

(x:xs)不是任意列表/字符串,它是一個非空列表/字符串,其頭部為x尾部為xs 因此

buildTree' (x:xs)  currenttree 
   ...

只處理非空列表。 使用-Wall編譯會警告缺少空列表案例。 所以,你需要:

buildTree' [] currenttree = ...
buildTree' (x:xs)  currenttree 
   ...

調整您的代碼,我們可以刪除null保護:

buildTree' [] currenttree = ("empty", currenttree)
buildTree' (x:xs)  currenttree 
   | isDigit x && ( take 1  xs == ['+'] ||  take 1 xs == ['-'])= buildTree' xs (Node [x] Empty Empty)
   ...

類似地, take檢查需要的不僅僅是列表的頭部x 你可以寫,而不是:

buildTree' [] currenttree = ("empty", currenttree)
buildTree' (x1:x2:xs)  currenttree 
   | isDigit x1 && ( x2 == '+' || x2 == '-') = buildTree' (x2:xs) (Node [x1] Empty Empty)
   ...

甚至

buildTree' [] currenttree = ("empty", currenttree)
buildTree' (x1:x2:xs)  currenttree 
   | isDigit x1 && (x2 `elem` "+-") = buildTree' (x2:xs) (Node [x1] Empty Empty)
   ...

我不知道你的邏輯是否正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM