函数-Haskell中的非穷举模式

时间:2013-11-12 21:14:25

标签: haskell insert binary-tree literate-programming non-exhaustive-patterns

我编写了一个函数,它将一个元素插入一个二进制树中,但每次我尝试运行它时,我都会在函数中得到一个非详尽的模式。

type Eintrag = (Person, Anschrift, SozNr)

data Tree = Nil | Node Eintrag Tree Tree deriving (Eq, Show)

singleton :: Eintrag -> Tree
singleton x = Node x Nil Nil

genTree :: Eintrag -> Tree-> Tree
genTree x (Node e l r)= if ((Node e l r)==Nil)
    then (singleton  x)
    else if (soznr x) < (soznr e )
            then (Node e (genTree x l) r)
            else if (soznr x) > (soznr  e )
                    then (Node e l (genTree x r))
                    else (Node e l r)
你可以给我一些提示吗? 感谢

3 个答案:

答案 0 :(得分:4)

你没有包含一个定义,当你插入的树是Nil时会发生什么,大概看起来像

genTree x Nil = singleton x

您尝试使用

行执行此操作
genTree x (Node e l r) = if (Node e l r == Nil)
    then singleton x
    else ...

但是如果你考虑一下,你会发现它无法奏效。模式匹配可确保您正在查看的树的格式为Node _ _ _,因此它永远不会Nil。也就是说,if表达式中的测试始终评估为False

答案 1 :(得分:1)

我得到的错误(在为代码添加一些定义以使其编译之后)是:

 Warning:
  Pattern match(es) are non-exhaustive
  In an equation for `genTree': Patterns not matched: _ Nil

这告诉您需要添加如下情况:

genTree x Nil = ...

答案 2 :(得分:0)

如果您将以下内容添加到文件的顶部(假设您使用的是GHC),它会告诉您确切的位置&#34;非详尽模式&#34;错误是 -

{-# OPTIONS_GHC -Wall #-}

正如其他人已经提到的那样,你错过了Nil案例。