Assertions in Haskell

Sometime back, I posted how to solve the Monty Hall problem with a million doors. Christophe Poucet wondered if I was making a mistake in my solution: maybe I was not ensuring that the host is not opening a door with a car. I did not think so, but then I have been wrong in the past.  So, I wanted to check my solution. First I thought of using QuickCheck to test if the host function was correct, but that would mean that I write a test property and then call it to check that everything was correct. And then make sure that there was no difference between the test and the main problem. But I am lazy, and wanted an easier solution. Enter the assert function from Control.Exception. I just made two changes in my previous program.

  1. I added a new import
    import Control.Exception (assert)
  2. I changed the randomVariable function to
    randomVariable :: (Door -> [Door] -> Door) -> MC Double
    randomVariable strategy = do
      u <- nature
      c <- contestant
      h <- host (options u c)
      let r = assert (all (\d -> open u d == Goat) h) $ reward u (strategy c h)
      return r

recompiled the code, and voila, no error messages. This means that my reasoning was correct. And now I can assert that my reasoning is correct. See GHC documentation and Haddock for more details on assertions.


One thought on “Assertions in Haskell

  1. I feel honored for the blogpost in my name. Checking your code now that I can focus on just this tiny bit. I see why it would always be correct. It is not that ‘host’ is correct, it is that ‘options’ ensures to return a list that only contains Goats.

    I missed the fact you did (host (options u c)). Instead of just calling host on the full remainder of doors.

    Very thorough!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s