Test
Test

Reputation: 95

How to put and get values from this dictionary I implemented

so after a bunch of trial and error, I'm pretty sure this is what it's supposed to be.

type ('a,'b) dict3 = ('a -> 'b option)

let empty3 : unit -> ('a,'b) dict3 =  fun x -> (fun y ->  None);;

let put3 : 'a -> 'b -> ('a,'b) dict3 -> ('a,'b) dict3 = fun key value dict -> fun x -> if x = key then Some value else dict x;;

let get3 : 'a -> ('a,'b) dict3 -> 'b option = fun key dict -> dict key;;

But now that I have this, I'm very confused how they communicate with one another. I tried doing a test for get3, and I came up with:

let _ = assert (get3 42 (fun lst -> Some (String.length "charizard")) = Some 9);;

which I think is correct. But I don't know how to write an assert case for put3, as I don't know how to show the ('a, 'b) dict3, nor how to get empty3 to return None.

Upvotes: 0

Views: 255

Answers (2)

molbdnilo
molbdnilo

Reputation: 66441

I suspect empty3 is supposed to be an empty dictionary, not a function that creates an empty dictionary, so you probably want

let empty3 : ('a,'b) dict3 =  fun _ ->  None;;

Your test case for get3 isn't very useful, as the dictionary that returns 9 for every key isn't one you can construct using empty3 and put3, so you're not giving get3 a valid dictionary.
This means that the test provides no information.

What you should test is that your functions implement a dictionary with specific properties, not that the dictionary has a specific structure.
(Your tests should work regardless of the representation of an ('a,'b) dict3.)

You have three cases that you need to test:

  • If d is the empty dictionary, get3 k d is None.
  • If d isn't the empty dictionary, but doesn't contain a value for k, get3 k d is None.
  • If d isn't the empty dictionary, and contains the value v for k, get3 k d is Some v.

These would provide useful information:

let _ = assert (get3 43 empty3 = None);;
let _ = assert (get3 43 (put3 44 9 empty3) = None);;
let _ = assert (get3 43 (put3 43 9 empty3) = Some 9);;

Upvotes: 1

George Leung
George Leung

Reputation: 1552

I want to have it as a comment, but I need 50 reputation for that, so I try to write a little bit more.

put3 gives a new function, which cannot be compared if I remember correctly. I do not think there is anything to assert.

Perhaps try putting something and then retrieve it using get3 and assert the values are the same?

Getting empty3 to return None is the easiest. You assert you get None from empty3()

assert (get3 "foo" (empty3 ()) = None);;

BTW I think empty3 should be written as fun () -> fun _ -> None if you want to keep the type signature.

Or simply fun _ -> None.

Upvotes: 1

Related Questions