在Isabelle中搜索树中的元素

时间:2014-10-27 14:06:27

标签: binary-tree isabelle

我有这个函数测试一个元素是否在二叉树中:

fun lookup::"int⇒bst⇒bool" where
"lookup x _ = false" |
"lookup x bst = ( if x = root(bst) then true else if x≤root(bst) then lookup x left(bst)  else    lookup x right(bst))" 

我收到错误消息 类型统一失败: 类型的冲突" bst"和" int"

数据类型bst定义为

  datatype bst  = Leaf | Node int bst bst

这里有什么问题?

2 个答案:

答案 0 :(得分:1)

看起来您的数据类型声明未提及叶子的任何关联值。所以,它可能看起来像

datatype_new bst  = Leaf int | Node int bst bst

然后该函数只检查当前节点的所有构造函数:

fun lookup :: "int ⇒ bst ⇒ bool" where
    "lookup x (Leaf y) = x = y" |
    "lookup x (Node y leftbst rightbst) =
        (if x = y then True
         else (if x ≤ y then lookup x leftbst else lookup x rightbst))"

答案 1 :(得分:0)

简短的回答是你误用了rootNthRoot.root来自src/HOL/NthRoot.thyroot的类型显示在错误消息中:

root :: nat => real => real

我CNTL点击了root,它将我带到了NthRoot.thy中的功能。

从这里开始,我基本上抱怨你让我比我想要的更努力,回答你的问题,即使是现在,我也认为我做了一个与你所说的重复的THY。

你在评论中给了我这句话:“导入主树”。但是,在仅使用Main进行THY之后,THY显然不是您正在做的事情,因为我没有收到错误消息Type unification failed: Clash of types "bst" and "nat"

theory Scratch
imports Main "~~/src/HOL/Library/Tree"
begin
datatype bst  = Leaf | Node int bst bst

fun lookup :: "int ⇒ bst ⇒ bool" where
  "lookup x _ = false" |
  "lookup x bst = (if x = root(bst) then true else if x ≤ root(bst)
                   then lookup x left(bst)  else    lookup x right(bst))"              
end

此外,在THY中,root未定义,它是一个变量。我从两个方面看到了这一点。我试着用CNTL点击它,什么都没发生。然后我注意到它是蓝色的,这意味着它是一个局部变量。

因此,我导入了Complex_Main,如下所示,我收到了您正在谈论的错误消息。我对二叉树一无所知,但错误消息中显示的root类型可以很快告诉您root很可能不是您想要的,因为它使用real。< / p>

theory Scratch2
imports Complex_Main
begin
datatype bst  = Leaf | Node int bst bst

fun lookup :: "int => bst => bool" where
  "lookup x _ = false" |
  "lookup x bst = (if x = root(bst) then true else if x ≤ root(bst) 
                   then lookup x left(bst)  else    lookup x right(bst))"
(*Type unification failed: Clash of types "bst" and "nat"

  Type error in application: incompatible operand type

  Operator:  root :: nat => real => real*)
end

无论如何,人们不希望在问题中看到太多的来源,他们不希望看到太少。如果你提供魔法数量,他们所要做的就是剪切和粘贴,那么他们就不必努力回答你的问题了。

从上一个问题Predefined functions for Binary trees in Isabelle开始,我知道从安德烈亚斯那里得到Tree的位置。

Andreas是像我和你这样的人的答案人。如果你想增加像他这样的人回答问题的机会,那么你希望他尽可能少地工作来找出你的问题。

一个简单的工作示例可以帮助确保每个人都在同一页面上,甚至在你提出问题之前就会发现一些错误。