Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Last active August 29, 2015 14:07
Show Gist options
  • Save markhibberd/0e25672726916c92db77 to your computer and use it in GitHub Desktop.
Save markhibberd/0e25672726916c92db77 to your computer and use it in GitHub Desktop.

A Basic GADT Challenge

  • I have a bag of stuff.
  • My bag is awesome it can hold different types of things allocated by a name.
  • My bag is kind of ok, in that it can only hold certain types of things. Specifically it can hold Int's, String's and Bool's. But this also makes it convenient to access those things.
  • Conveniently the key tells me what type to expect.

In my haskell2010 world, I implement this as a simple data type:

data Key = Key String
data Value = I Int | S String | B Bool
data Bag = Bag [(Key, Value)]

And I can implement things like:

getBool :: Bag -> Key -> Either String (Maybe Bool)

But this is obviously less than desirable, I have two errors to handle:

  1. Whether the value exists or not
  2. Whether the value was a bool

I also didn't use the info, that I know the type based on my key.

Lets build better a Key data type such that it encodes the type of the value, and then change value, such that it can only be indexed by an appropriately typed key.

@etorreborre
Copy link

I guess it should be "Whether the list is empty or not".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment