【发布时间】: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 中比使用守卫更惯用 - 但守卫可以做的更多,所以有时你确实需要它们。