Source

ollio / vector.ml

Full commit

(* module vector *)

exception Invalid_vector;;
exception Length_unmatch;;

let print_vector x =
  let rec p = function
    | [] -> print_endline ")";
    | (i,v)::tl ->
      Printf.printf "%d:%f " i v;
      p tl
  in
  print_string "(";
  p x;;

(* 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);
      | (i,ix)::tlx, (j,jy)::_ when i<j->
	add_ tlx yy ((i,ix)::v);
      | (i,ix)::_, (j,jy)::tly when i>j->
	add_ xx tly ((j,jy)::v);
      | [], hd::tl -> add_ tl [] (hd::v);
      | hd::tl ,[] -> add_ tl [] (hd::v);
      | _,_ -> raise Invalid_vector;
  in
  add_ x y [];;

let make n v =
  let rec make_ x = function
    | 0 -> List.rev x;
    | i -> make_ ((i,v)::x) (i-1)
  in
  make_ [] n;;

let newv() =
  make 0 0.0;;

(* get norm of x with rank 2 *)
let norm2 x =
  let rec norm_ s = function
    | [] -> s;
    | (_,v)::tl ->
      norm_ (s +. v *. v) tl
  in
  norm_ 0.0 x;;