Ocaml - Iterative to recursion

For the assignment, I wrote the following code in recursion. It takes a list of a vector datatype and a vector and computes the closeness of the two vectors. This method works great, but I don't know how to make 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 would be much appreciated

+2


source to share


1 answer


General recursive equivalent

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

      

:



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

      

Note that just like the for-loop, this function only returns one, although you can define a similar recursive function that returns a meaningful value (and in fact what it does most). You can also use List.iter, which is just for this situation, where you are using an impure function that doesn't return anything meaningful for every item in the list:

List.iter f x

      

+3


source







All Articles