简体   繁体   English

Ocaml树简单功能

[英]Ocaml Tree simple functions

I created a tree 我创造了一棵树

type 'a tree = {
      mutable cont: 'a;
      mutable left: 'a bin_tree;
      mutable right: 'a bin_tree
}
and 'a bin_tree =
     Empty
     | Node of 'a tree;;

and I'm struggling to do with some simple functions like 我正在努力处理一些简单的功能,例如

  • insertion of elements (to the propper subtrees, no duplicates) 插入元素(到适当的子树,没有重复)
  • making union of two binary trees 使两个二叉树合并

I googled my problem but I'm constantly getting errors. 我用谷歌搜索了我的问题,但我不断出错。 For example: 例如:

let rec insert x tree =
match tree with
 Empty -> Node(x, Empty, Empty)
| Node(y, left, right) ->
   if x <= y then Node(y, insert x left, right)
             else Node(y, left, insert x right)

or if I try: 或者,如果我尝试:

let rec insert x = function
Empty -> Node(Empty, x, Empty)
| Node(lb, r, rb) -> if x < r then Node(insert x lb, r, rb)
else Node{lb; r; insert x rb} ;;

I'm constantly getting Syntax Error. 我不断收到语法错误。

Why do you use a mutable record for your tree? 为什么为树使用可变记录? OCaml programmers prefer to use immutable data structures. OCaml程序员更喜欢使用不可变的数据结构。 Here the mutability of your tree doesn't improve the complexity but can introduce bugs. 在这里,树的可变性不会提高复杂性,但会引入错误。

Here is how to implement trees in a persistent way: 以下是以持久方式实现树的方法:

type 'a tree =
| Empty
| Node of 'a * 'a tree * 'a tree

and it is actually this type that you use in your code for member and insert . 实际上,您在代码中为memberinsert使用的就是这种类型。

Your match pattern should contain { and } to match a record so code 您的匹配模式应包含{}以匹配记录,因此代码

match tree with
   Empty -> false
  | Node { cont=x; left=l; right=r } -> (*something here .... *)

Actually, a language extension for record notation permit to avoid the field labels when the pattern variable has the same name as the field, so instead of coding a pattern Node { cont=cont; left=left; right=right } 实际上,当模式变量具有与字段相同的名称时, 用于记录表示法语言扩展允许避免使用字段标签,因此,无需编码模式Node { cont=cont; left=left; right=right } Node { cont=cont; left=left; right=right } Node { cont=cont; left=left; right=right } you can code Node{cont;left;right} Node { cont=cont; left=left; right=right }您可以编写Node{cont;left;right}

You could also look into Ocaml's stdlib/set.ml source file. 您也可以查看Ocaml的stdlib / set.ml源文件。

Notice that your 'a bin_tree type is nearly equivalent to 'a tree option . 注意,您的'a bin_tree类型几乎等同于'a tree option

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM