Dagoo Mong
Dagoo Mong

Reputation: 107

ocaml type clarification (beginner)

I have this declaration

type 'a dict = string -> 'a option
val empty : unit -> 'a dict
val insert : 'a dict -> string * 'a -> 'a dict

following this declaration, how can I write empty ? empty () just returns an empty dictionary.

Upvotes: 2

Views: 63

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

I don't want to short-circuit the part where you figure things out for yourself. Here are hints.

  1. A dictionary has the type string -> 'a option. I.e., it's a function that returns what you're looking for in the dictionary or None if the string isn't associated with a value in the dictionary. Seems like an empty dictionary is one where no string is associated with anything, so the function would always return the same result. It's not so hard to write a function that always returns the same thing.

  2. Your code is returning the value (of type 'a) but it's supposed to return something of type 'a option. Otherwise it's great code, you are grasping the point of it (IMHO).

Upvotes: 2

Related Questions