Leal9001

Aula 3

Mar 19th, 2018
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.34 KB | None | 0 0
  1. type 'a tree = Nil | Node of 'a * 'a tree * 'a tree;;
  2.  
  3. type 'a ntree = NNil | NNode of 'a * 'a ntree list
  4.  
  5. let rec howMany v t =
  6.     match t with
  7.     | Nil -> 0
  8.     | Node(x,l,r) -> (if v = x then 1 else 0)
  9.     + howMany v l + howMany v r;;
  10.  
  11. let rec eqPairs t =
  12.     match t with
  13.     | Nil -> 0
  14.     | Node((x,y),l,r) -> (if x = y then 1 else 0)
  15.     + eqPairs l + eqPairs r;;
  16.  
  17. let rec treeToList t =
  18.     match t with
  19.     | Nil ->  []
  20.     | Node(x, l, r) -> x :: (treeToList l @ treeToList r);;
  21.  
  22. let rec height t =
  23.     match t with
  24.         | Nil -> 0
  25.     | Node(x,l,r) ->
  26.            1 + max (height l) (height r);;
  27.  
  28. let rec balanced t =
  29.     match t with
  30.     | Nil -> true
  31.     | Node(x, l, r) -> if (abs(height l - height r) > 1) then
  32.         false else balanced l && balanced r;;
  33.  
  34. let rec subtrees t =
  35.     match t with
  36.     | Nil -> []
  37.     | Node(x, l, r) -> Node(x, l, r) :: (subtrees l @ subtrees r);;
  38.  
  39. let rec spring v t =
  40.     match t with
  41.     | Nil -> Node(v, Nil, Nil)
  42.     | Node(x, l, r) -> Node(x, spring v l, spring v r);;
  43.  
  44. spring 2 Node(3, Node(2, 4, Nil), Nil);;
  45.  
  46. let rec fall t =
  47.     match t with
  48.     | Nil -> Nil
  49.     | Node(x, Nil, Nil) -> Nil
  50.     | Node(x, l, r) -> Node(x, fall l, fall r);;
  51.  
  52. let rec spring v nt =
  53.     match nt with
  54.     | NNil -> NNode(v, [])
  55.     | NNode(x, cs) -> NNode(x, lspring v cs);;
  56.  
  57.  
  58. let rec lspring v l =
  59.     match l with
  60.     | [] -> []
  61.     | t:ts -> spring v t :: lspring ts;;
Advertisement
Add Comment
Please, Sign In to add comment