2

I have this function:

let rec  som a b acc = 
if a > b then acc else 
som (a+1) b (acc+(comb b a));;

And what I am trying to do is to save acc value in a hashtable, so my first try was:

let rec  som a b acc = 
if a > b then acc else 
som (a+1) b (acc+(comb b a)) Hashtbl.add a acc;;

but it does not work... How can I save the values?

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281

2 Answers2

2

This is skeleton, you can try to add you code into it to get what you want. Maybe it will be helpful.

module Key = struct 
   type t=int
   let compare: t->t->int = fun a b -> (* return -1 if a<b, 0 if a=b,and 1 if a>b *)
   let equal = (=)
end
module H=Hashtbl.Make(Key)
let som =
   let h = H.create () in
   let rec f a b acc =
     try H.find h acc 
     with Not_found ->
       let ans = (* your evaluation code *) in
       H.add h acc ans;
       ans
   in
   f
Kakadu
  • 2,837
  • 19
  • 29
0

First, let's take a look at the signature of Hashtbl.add

('a, 'b) Hashtbl.t -> 'a -> 'b -> unit = <fun> 

The first argument of the function is an hash table, then you need to create one. To do it, write let h_table = Hashtbl.create 123456;;. And to put it in context your add instruction become HashTbl.add h_table a acc

Next, you can't call this function at the same level of the recursive call. Indeed the function som take three arguments and you will face the following error message, It is applied to too many arguments ....

And as you want to trace the value of acc you need to put it before the recursive call. Doing this can lead you to face some difficulty, then I've added below a hint.

let _ = Printf.printf "a\n" in 
  let _ = Printf.printf "b\n" in 
    (1+2)
;;
a
b                                                                                       
- : int = 3
zurgl
  • 1,930
  • 1
  • 14
  • 20