Created
May 17, 2019 06:55
-
-
Save 23Skidoo/304113b6b2cda90fec4075941cf3b9a0 to your computer and use it in GitHub Desktop.
This file contains 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 AllowAmbiguousTypes #-} | |
{-# LANGUAGE TypeApplications #-} | |
{-# LANGUAGE ScopedTypeVariables #-} | |
{-# LANGUAGE MultiParamTypeClasses #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
import Control.Monad | |
data MobileField = MobileField String | |
data EmailField = EmailField String | |
data Field = MF MobileField | EF EmailField | |
class HasFieldOfType f s where | |
getFieldOfType :: s -> Maybe f | |
instance HasFieldOfType MobileField Field where | |
getFieldOfType (MF f) = Just f | |
getFieldOfType _ = Nothing | |
instance HasFieldOfType EmailField Field where | |
getFieldOfType (EF f) = Just f | |
getFieldOfType _ = Nothing | |
mobileNumber :: MobileField -> String | |
mobileNumber (MobileField x) = x | |
emailAddress :: EmailField -> String | |
emailAddress (EmailField x) = x | |
foo :: forall f . HasFieldOfType f Field => [Field] -> Maybe f | |
foo = msum . map (getFieldOfType @ f) | |
fields :: [Field] | |
fields = [MF (MobileField "+4412345678"), EF (EmailField "[email protected]")] | |
main :: IO () | |
main = do | |
print $ mobileNumber <$> foo @MobileField fields | |
print $ emailAddress <$> foo @EmailField fields |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment