views:

210

answers:

1

For an assignment, i have written the following code in recursion. It takes a list of a vector data type, and a vector and calcuates to closeness of the two vectors. This method works fine, but i dont know how to do the recursive version.

let romulus_iter (x:vector list ) (vec:vector) = 
     let vector_close_hash = Hashtbl.create 10 in 
     let prevkey = ref 10000.0 in (* Define previous key to be a large value since we intially want to set closefactor to prev key*)
     if List.length x = 0 then
      {a=0.;b=0.}
     else
      begin
      Hashtbl.clear vector_close_hash ; 
      for i = 0 to (List.length x)-1 do
       let vecinquestion = {a=(List.nth x i).a;b=(List.nth x i).b} in
       let closefactor = vec_close vecinquestion vec in
       if(closefactor < !prevkey) then 
        begin
         prevkey := closefactor;
         Hashtbl.add vector_close_hash closefactor vecinquestion
        end
       done; 
        Hashtbl.find vector_close_hash !prevkey
      end;;

Any help will be much appreciated

+3  A: 

The general recursive equivalent of

for i = 0 to (List.length x)-1 do
    f (List.nth x i)
done

is this:

let rec loop = function
  | x::xs -> f x; loop xs
  | [] -> ()

Note that just like a for-loop, this function only returns unit, though you can define a similar recursive function that returns a meaningful value (and in fact that's what most do). You can also use List.iter, which is meant just for this situation where you're applying an impure function that doesn't return anything meaningful to each item in the list:

List.iter f x
Chuck
Thanks man, it clicked finally!
Faisal Abid