Sunday 15 June 2014

memorization - Why the type of this OCaml code snippet is wrong? -



memorization - Why the type of this OCaml code snippet is wrong? -

i learning concept of memorized function in ocaml, , tried implement myself.

here code wrote:

type 'a memo_type = value of 'a | exn of exn allow memo_func_hash_exp f = allow cache = hashtbl.create 10 in fun v -> seek match hashtbl.find cache v | value r -> r | exn e -> e | not_found -> begin seek allow r = f v in hashtbl.replace cache v (value r); r | e -> hashtbl.replace cache v (exn e); raise e end ;;

however, surprise, interpreter shows me type of function memo_func_hash_exp this:

val memo_func_hash_exp : ('a -> exn) -> 'a -> exn = <fun>

it seems wired , have no thought part of implementation goes wrong..

consider type of expression:

match hashtbl.find cache v | value r -> r | exn e -> e

in cases returns r , in other cases returns e. hence these must same type. since cache value of function r , exceptions e follows r exception.

it's more want raise exception if that's what's in table.

ocaml memorization

No comments:

Post a Comment