Skip to content

Instantly share code, notes, and snippets.

@zobar
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save zobar/390bc65f43d5175887f0 to your computer and use it in GitHub Desktop.

Select an option

Save zobar/390bc65f43d5175887f0 to your computer and use it in GitHub Desktop.
contrived value input =
let parsed = read input in -- parsed implements Read
-- read takes a String, therefore input must be String
if parsed == value -- parsed & value are same type, which implements Eq
then Just parsed
else Nothing
{-
If type bindings are still ambiguous after the function is defined, it's
preferred to leave them unresolved rather than forcing them. This keeps your
function as generic as possible (think duck-typing). Therefore:
contrived :: (Read a, Eq a) => a -> String -> Maybe a
...which you can prove with ghci:
$ ghci contrived.hs
*Main> :t contrived
contrived :: (Read a, Eq a) => a -> String -> Maybe a
*Main> contrived True "True"
Just True
*Main> contrived True "False"
Nothing
*Main> contrived True "1"
*** Exception: Prelude.read: no parse
*Main> contrived 1 "1"
Just 1
* magic *
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment