Skip to content

Instantly share code, notes, and snippets.

@23Skidoo
Created May 17, 2019 06:55
Show Gist options
  • Save 23Skidoo/304113b6b2cda90fec4075941cf3b9a0 to your computer and use it in GitHub Desktop.
Save 23Skidoo/304113b6b2cda90fec4075941cf3b9a0 to your computer and use it in GitHub Desktop.
{-# 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