Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a basic Closure example in ocaml

Tags:

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?

like image 469
Knows Not Much Avatar asked May 31 '26 12:05

Knows Not Much


1 Answers

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.

like image 87
camlspotter Avatar answered Jun 02 '26 21:06

camlspotter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!