Ocaml Tree simple functions

点点圈 提交于 2019-12-11 20:44:57

问题


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.


回答1:


Why do you use a mutable record for your tree? OCaml programmers prefer to use immutable data structures. 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.




回答2:


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 } you can code Node{cont;left;right}

You could also look into Ocaml's stdlib/set.ml source file.

Notice that your 'a bin_tree type is nearly equivalent to 'a tree option.



来源:https://stackoverflow.com/questions/16507273/ocaml-tree-simple-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!