我想在榆樹中製作一個高效版本的LCS算法。 我喜歡這個ocaml版本,但它使用副作用來緩存結果。榆樹中最長的常見子序列與記憶
let lcs xs ys =
let cache = Hashtbl.create 16 in
let rec lcs xs ys =
try Hashtbl.find cache (xs, ys) with
| Not_found ->
let result =
match xs, ys with
| [], _ -> []
| _, [] -> []
| x :: xs, y :: ys when x = y ->
x :: lcs xs ys
| _ :: xs_rest, _ :: ys_rest ->
let a = lcs xs_rest ys in
let b = lcs xs ys_rest in
if (List.length a) > (List.length b) then a else b
in
Hashtbl.add cache (xs, ys) result;
result
in
lcs xs ys
我應該怎麼做,如果我想在榆樹中使用memoization?
即使懶惰我仍然看不到我如何傳遞遞歸調用的不同分支之間的值。 –