Created
July 15, 2015 09:58
-
-
Save davidpdrsn/6bd4a8eb40daf7a118ca 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
| module Optional where | |
| data Optional a = Some a | |
| | None | |
| instance Functor Optional where | |
| fmap f (Some x) = Some (f x) | |
| fmap _ None = None | |
| instance Applicative Optional where | |
| pure x = Some x | |
| Some f <*> Some x = Some (f x) | |
| _ <*> _ = None | |
| instance Monad Optional where | |
| return x = Some x | |
| Some x >>= f = f x | |
| _ >>= _ = None | |
| data User = User { firstname :: String | |
| , lastname :: String | |
| } | |
| findUser :: Int -> Optional User | |
| findUser 1 = Some User { firstname = "Christian" | |
| , lastname = "Planck" | |
| } | |
| findUser _ = None | |
| userFullName :: User -> String | |
| userFullName user = firstname user ++ " " ++ lastname user | |
| usingFmap :: Optional String | |
| usingFmap = | |
| let | |
| user = findUser 1337 -- None ... | |
| in fmap userFullName user | |
| getFirstname :: Optional String | |
| getFirstname = Some "Christian" | |
| getLastname :: Optional String | |
| getLastname = Some "Planck" | |
| usingApply :: Optional User | |
| usingApply = User <$> getFirstname <*> getLastname | |
| type Ranking = String | |
| getRankings :: User -> Optional Ranking | |
| getRankings _user = Some "Top score!!" | |
| usingBind :: Optional Ranking | |
| usingBind = | |
| let | |
| user = findUser 1 -- Some ... | |
| in user >>= getRankings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment