Last active
August 29, 2015 14:07
-
-
Save zobar/390bc65f43d5175887f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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