Function OCaml-将递归函数的值保存在哈希表中
我有这个功能:Function OCaml-将递归函数的值保存在哈希表中,function,recursion,ocaml,hashtable,Function,Recursion,Ocaml,Hashtable,我有这个功能: let rec som a b acc = if a > b then acc else som (a+1) b (acc+(comb b a));; 我要做的是将acc值保存在哈希表中,所以我的第一次尝试是: let rec som a b acc = if a > b then acc else som (a+1) b (acc+(comb b a)) Hashtbl.add a acc;; 但它不起作用。。。如何保存这些值?这是一个框架,您可以尝
let rec som a b acc =
if a > b then acc else
som (a+1) b (acc+(comb b a));;
我要做的是将acc值保存在哈希表中,所以我的第一次尝试是:
let rec som a b acc =
if a > b then acc else
som (a+1) b (acc+(comb b a)) Hashtbl.add a acc;;
但它不起作用。。。如何保存这些值?这是一个框架,您可以尝试向其中添加代码以获得所需的内容。也许会有帮助
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
module Key=struct
类型t=int
让我们比较:t->t->int=funab->(*如果ab*返回-1)
设相等=(=)
结束
模块H=Hashtbl.Make(键)
让索姆=
让h=h.create()在
让我们记录a b acc=
试试H.find H acc
在未找到的情况下->
让ans=(*您的评估代码*)输入
H.添加H acc ans;
ans
在里面
F
<代码> > P>首先,让我们看看“代码> Hashtbl的签名。添加< /COD> < /P>
('a, 'b) Hashtbl.t -> 'a -> 'b -> unit = <fun>
非常感谢你的帮助
let _ = Printf.printf "a\n" in
let _ = Printf.printf "b\n" in
(1+2)
;;
a
b
- : int = 3