Last active
March 2, 2019 13:17
-
-
Save mbbx6spp/3793c45bbb6f24ad705e1bc3f5d8fe13 to your computer and use it in GitHub Desktop.
Example demonstrating Alternative
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
| {-# LANGUAGE NoImplicitPrelude #-} | |
| module AlternativeExample where | |
| import Control.Applicative | |
| import Data.Maybe | |
| import Data.Text hiding (empty) | |
| import GHC.Show (Show) | |
| type Login = Text | |
| type Email = Text | |
| type Bio = Text | |
| data User = MkUser Login Email Bio deriving (Show) | |
| -- In a real world application this would be validating if the @Login@ is valid (no curse words, or whatever that means) | |
| getFormLogin :: Applicative f => f Login | |
| getFormLogin = pure "curlyfries" | |
| -- In a real world application this would be validating the format of the email address given in the form | |
| getFormEmail :: Applicative f => f Email | |
| getFormEmail = pure "[email protected]" | |
| -- In a real world application this would check for spam or something | |
| getFormBio :: Applicative f => f Bio | |
| getFormBio = pure "Here is the bio for this user." | |
| -- Not sure having a default user makes sense in all systems, but it might. | |
| defaultUser :: User | |
| defaultUser = MkUser "admin" "[email protected]" "some bio" | |
| baseExpr :: Applicative f => f Bio -> f User | |
| baseExpr bio = MkUser <$> getFormLogin <*> getFormEmail <*> bio | |
| -- Produces | |
| -- >>> expr0 | |
| -- Just (MkUser "curlyfries" "[email protected]" "Here is the bio for this user.") | |
| expr0 :: Maybe User | |
| expr0 = baseExpr getFormBio <|> pure defaultUser | |
| -- Produces | |
| -- >>> expr1 | |
| -- Just (MkUser "admin" "[email protected]" "some bio") | |
| expr1 :: Maybe User | |
| expr1 = baseExpr Nothing <|> Just defaultUser | |
| -- Produces | |
| -- >>> expr2 | |
| -- Nothing | |
| expr2 :: Maybe User | |
| expr2 = baseExpr Nothing <|> Nothing | |
| -- TL;DR the applicative interface allows you to build up expressions that inject fully formed values into a context and | |
| -- the alternative interface gives you the ability to provide alternative/"otherwise" paths in expressions such that | |
| -- more logic can be composed around it in these contexts or via these or related interfaces. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment