Knows Not Much
Knows Not Much

Reputation: 31526

Understanding a basic Closure example in ocaml

I am reading this article on stack overflow

How to implement a dictionary as a function in OCaml?

I think the problem statement is to create a dictionary object by using Closures.

However i am finding the closure very difficult to understand.

the problem I am facing is

As per the answer of the thread I posted above, I typed the following code in OCAML REPL

let empty (_ : string) : int = 0;;
let add d k v = fun k' -> if k = k' then v else d k;;
let d = add empty "foo" 10;;
let d1 = add d "bar" 20;;

Now if I do

d1 "foo"

it returns 0.

But this is wrong!. I have build d1 from d. therefore both "foo" and "bar" must be found in the dictionary.

Had I implemented this dictionary using a non-closure approach, it would have been very easy for me to search my list and of-course both "foo" and "bar" would be found.

What am I missing here?

Upvotes: 3

Views: 2203

Answers (1)

camlspotter
camlspotter

Reputation: 9030

Your add is not correct. If one closure fails to find the given key k', it must ask the underlying closure about the same k', not k.

The correct answer is:

let add d new_k new_v = fun query_k -> if new_k = query_k then v else d query_k

Sometimes verbose argument names may help to avoid this kind of bugs.

Upvotes: 6

Related Questions