Commit 91ee9611 authored by Andreas Pfurtscheller's avatar Andreas Pfurtscheller

Add HW07 馃搫

parent 73862d77
......@@ -25,13 +25,13 @@ type graph = (int * float * int) list
(**************************** HOMEWORK STARTS HERE ***************************)
(*****************************************************************************)
(* Assignment 7.4 [7 points] *)
let f1 = todo
let f2 = todo
let f3 = todo
let f4 = todo
let f5 = todo
let f6 = todo
let f7 = todo
let f1 = (fun a b -> (a+1))
let f2 = (fun a b -> if (List.fold_left f1 0 a) > (List.fold_left f1 0 b) then a else b)
let f3 = (fun a (x,y) -> a@[(y,x)])
let f4 = (fun a b -> if ((List.fold_left f1 0 a) mod 2) = 0 then b::a else a@[b])
let f5 = (fun f (k,v) -> (fun x -> if k=x then v else (f x)))
let f6 = (fun (h::tl) f -> (f h)::h::tl)
let f7 a ci = (a * a) * ci
(*****************************************************************************)
(* Assignment 7.5 [7 points] *)
......@@ -50,12 +50,45 @@ let rec eval_expr (s : state) (e : expr) : value =
| Div -> Rat (n1*d2,d1*n2))
| _ -> failwith "invalid type")
(* TODO: continue here *)
| Func (a, exp) -> Fun (a, s, exp)
| Ite (c, t, e) -> (match (eval_expr s c) with
| Rat (0,_) -> (eval_expr s e)
| _ -> (eval_expr s t))
| _ -> todo ()
(*****************************************************************************)
(* assignment 7.6 [6 points] *)
let mst = todo
(* Get all nodes in the graph *)
let nodes g = List.sort_uniq compare (List.fold_left (fun a (x,w,y) -> x::y::a) [] g)
(* Get all adjacent nodes of n *)
let adj n g = List.fold_left (fun a (x,w,y) -> if x=n then (y,w)::a else if y=n then (x,w)::a else a) [] g
(* Build a list of (int * (int * float)), which is (node * (node * weight)) *)
let dst s g = List.map (fun x -> if x=s then (x, (0, 0.0)) else (x, (0, infinity))) g
let get_dist (n,d) = d
(* Sort nodes by their distances *)
let nodes_pq n d = List.sort (fun a b -> compare (get_dist (List.assoc a d)) (get_dist (List.assoc b d))) n
(* Run Prims algo on g *)
let mst g =
(* Runs on all nodes of g *)
let it go =
(* Runs on PQ and distances of g *)
let s = (List.hd go) in
let rec run n d r = match nodes_pq n d with
(* If the PQ is empty, we're done. Return our found r *)
| [] -> r
(* If the PQ is not empty, get the min node. *)
| u::tl ->
let fx = (fun l (v,w) -> if (List.exists (fun a -> a=v) tl) && (w < (get_dist (List.assoc v d))) then (v,(u,w))::(List.remove_assoc v l) else l) in
run tl (List.fold_left fx d (adj u g)) (List.fold_left fx r (adj u g)) in
List.filter (fun (v,(u,w)) -> (v!=s)) (run go (dst s go) []) in
List.map (fun (v,(u,w)) -> (u,w,v)) (it (nodes g))
(*****************************************************************************)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment