Advertisement
wandrake

Untitled

Jun 27th, 2013
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.23 KB | None | 0 0
  1. (*
  2.  *  Principi di Linguaggi di Programmazione
  3.  *  Modulo Paradigmi
  4.  *
  5.  *  Appello IV: 25/06/2013
  6.  *  Esercizio 2
  7.  *)
  8.  
  9. module type ITREE =
  10.   sig
  11.     type 'a tree
  12.     val newEmpty: 'a tree
  13.     val newVertex: 'a -> 'a tree
  14.     val addEdge: 'a tree -> 'a -> 'a -> 'a tree
  15.     val sons: 'a tree -> 'a -> 'a tree list
  16.   end;;
  17.  
  18. module ITree:ITREE =
  19.   struct
  20.     open List
  21.     type 'a tree = Empty | Node of 'a * 'a tree list
  22.  
  23.     let newEmpty = Empty
  24.     let newVertex a = Node(a, [])
  25.  
  26.     let inList l r =
  27.       let f x y =
  28.         match y with
  29.         | true -> true
  30.         | false -> (
  31.           match x with
  32.           | Node(v, _) when v = r -> true
  33.           | _ -> false
  34.         )
  35.       in List.fold_right f l false
  36.  
  37.     let rec addEdge t r s =
  38.       match t with
  39.       | Empty -> raise (Failure "Error")
  40.       | Node(x, l) when x = r -> (
  41.         if inList (sons r) s
  42.           then raise (Failure "Error")
  43.           else Node(x, (newVertex s)::l)
  44.         )
  45.       | Node(x, l) -> Node(x, List.map (fun x -> addEdge x r s) l)
  46.  
  47.     let rec sons t r =
  48.       let f x = sons x r
  49.       match t with
  50.       | Empty -> []
  51.       | Node(x, l) when x = r -> l
  52.       | Node(x, l) -> List.flatten (List.map f l)
  53.   end;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement