Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* tree.ml *)
- (* definicja drzewa *)
- type btree =
- Leaf of int
- | Node of btree * btree ;;
- (* val print_tree : btree -> unit;; *)
- let print_tree d =
- let rec string_of_tree d =
- match d with
- Leaf f -> string_of_int f
- | Node (n1,n2) -> " N("^string_of_tree n1^";"^string_of_tree n2^") "
- in Printf.printf "TREE -> [%s]\n" (string_of_tree d);;
- (* val sum : btree -> int *)
- let rec sum = function
- Leaf f -> f
- | Node (n1,n2) -> (sum n1) + (sum n2);;
- (* let sum tree =
- let rec sum_tree tree = function
- Leaf f -> f
- | Node (n1,n2) -> (sum_tree n1) + (sum_tree n2)
- in (sum_tree tree);; *)
- (* Dla kazdego liscia zaaplikuj funkcje *)
- (* val map : *)
- let map fx tree =
- let rec map_t= function
- Leaf l -> Leaf (fx l)
- | Node (n1,n2) -> Node((map_t n1),( map_t n2))
- in (map_t tree);;
- (* let rec map fx = function
- Leaf l -> Leaf(fx l)
- | Node(n1,n2) -> Node(map fx n1) *)
- (* val fold_left: (int -> int) -> int -> btree -> int;; *)
- let fold_left (red: int -> int -> int) seed tree =
- let rec reduce seed = function
- Leaf l -> red seed l
- | Node(n1, n2) -> reduce (reduce seed n1) n2
- in reduce seed tree;;
- (* val mount: int -> btree -> btree -> btree;; *)
- let mount v t1 t2 =
- let rec searchV v = function
- Leaf f -> if f=v then t2 else Leaf f
- | Node(n1, n2) -> Node((searchV v n1), (searchV v n2))
- in (searchV v t1);;
- (* pr_tree.ml *)
- open Printf;;
- open Tree;;
- let t3 = Node(Leaf 1, Leaf 2)
- let t1 = Node ( Node(Leaf 3, Leaf 3),
- Leaf 3);;
- let t2 = Node (
- Node(
- Node(Leaf 2, Leaf 4),
- Leaf 3
- ), Node(Leaf 1, Leaf 5)
- );;
- (* print_tree t1;; *)
- (* printf "%d\n" (sum t1);; *)
- (* printf "%d\n" (sum t2);; *)
- let fx = fun x -> x *10 + 1;;
- let red = fun x y -> x-y;;
- (* let mapped = map fx t1;; *)
- print_tree (map fx t2);;
- printf "%d\n" (fold_left red 10 t1);;
- print_tree t1;;
- print_tree t2;;
- print_tree (mount 3 t1 t3);;
- (* tree.mli *)
- (* definicja drzewa *)
- type btree =
- Leaf of int
- | Node of btree * btree ;;
- val print_tree : btree -> unit;;
- val sum : btree -> int;;
- val map : (int -> int) -> btree -> btree;;
- val fold_left: (int -> int -> int) -> int -> btree -> int;;
- val mount: int -> btree -> btree -> btree;;
- # Makefile tree
- all: pr_tree
- tree.cmi: tree.mli
- ocamlc -c tree.mli
- tree.cmo: tree.ml tree.cmi
- ocamlc -c tree.ml
- pr_tree: tree.cmi tree.cmo
- ocamlc -o tree tree.cmo pr_tree.ml
- clean:
- rm -r *.cmo *cmi tree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement