【问题标题】:Non-exhaustive patterns in function buildTree' Haskell函数 buildTree' Haskell 中的非详尽模式
【发布时间】:2020-01-03 08:50:06
【问题描述】:

我使用返回元组的函数。但是当我尝试运行该函数时,它给了我一个例外:函数中的非详尽模式。

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

【问题讨论】:

  • 看起来你确实在你的函数中做了太多。你真的应该尝试实现 simpler 函数,每个函数都做一件非常简单的事情。您可以使用-Wall 进行编译,Haskell 将显示问题所在。乍一看,你好像没有覆盖buildTree []
  • null (x:xs) 守卫并没有像我期望的那样做。 x:xs 是一个空列表永远无法匹配的模式。您需要一个单独的 buildTree' [] currentTree 模式来涵盖这种情况。一般来说,模式匹配在 Haskell 中比使用守卫更惯用 - 但守卫可以做的更多,所以有时你确实需要它们。

标签: haskell exception tuples


【解决方案1】:

(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)
   ...

我不知道你的逻辑是否正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多