Pabl0o0

Untitled

Nov 27th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. module type TREE =
  2. sig
  3. type 'a bst_t
  4.  
  5. val create: unit -> 'a bst_t
  6. val push: 'a -> 'a bst_t -> 'a bst_t
  7. val find: 'a -> 'a bst_t -> bool
  8. (* val remove: 'a -> 'a bst_t *)
  9. end;;
  10.  
  11.  
  12.  
  13.  
  14. module T : TREE =
  15. struct
  16. type 'a bst_t =
  17. | Leaf
  18. | Node of 'a bst_t * 'a * 'a bst_t (* Node (left, key, right) *)
  19. (* a node may also carry a data associated with the key.
  20. It is omitted here for neater demonstration *)
  21.  
  22. let create () = Leaf
  23.  
  24. let rec push x = function
  25. | Leaf -> Node (Leaf, x, Leaf) (* Leaf is a STOP *)
  26. | Node (left, k, right) ->
  27. if x < k then Node (push x left, k, right) (* if x is smaller, go left *)
  28. else Node (left, k, push x right) (* otherwise, go right *)
  29.  
  30. let rec find x = function
  31. | Leaf -> false
  32. | Node (left, k, right) ->
  33. if x < k then find x left
  34. else if x = k then true
  35. else find x right
  36.  
  37. end;;
  38.  
  39. T.create()
  40. T.push(5)
  41. T.push(3)
  42. T.push(1)
  43. T.push(4)
  44. T.push(7)
  45.  
  46. T.find(3)
Advertisement
Add Comment
Please, Sign In to add comment