Source

ollio / vector.ml

Full commit

(* module vector *)

exception Invalid_vector;;
exception Length_unmatch;;

(* assume x and y are soreted by its element *)
let prod x y =
  let rec prod_ xx yy v =
    match xx, yy with
      | [],_ | _,[] -> v;
      | (i,ix)::tlx, (j,jy)::tly when i=j ->
	prod_ tlx tly (v +. ix *. jy);
      | (i,ix)::tlx, (j,jy)::tly when i<j ->
	prod_ tlx yy v;
      | (i,ix)::tlx, (j,jy)::tly when i>j ->
	prod_ xx tly v;
      | _,_ ->
	raise Invalid_vector
  in
  prod_ x y 0.0;;

(* scalar product *)
let s_prod c vec =
  List.map (fun (i,v)-> (i, (c *. v))) vec;;

let add x y =
  let rec add_ xx yy v =
    match xx, yy with
      | [],_ | _,[] -> List.rev v;
      | (i,ix)::tlx, (j,jy)::tly when i=j->
	add_ tlx tly ((i, (ix +. jy))::v);
      | hdx::tlx, hdy::tly ->
	add_ tlx tly (hdx::hdy::v);
  in
  add_ x y [];;

let newv () = [];;