Skip to content

Instantly share code, notes, and snippets.

@decapo01
Created October 19, 2019 02:45
Show Gist options
  • Save decapo01/c7cddc279db9126900c5e506b99c5358 to your computer and use it in GitHub Desktop.
Save decapo01/c7cddc279db9126900c5e506b99c5358 to your computer and use it in GitHub Desktop.
Hasell show typeclass
import Data.Text
data MyCaseClass
= MyCaseClass
{ _id :: Int
, name :: Text
}
data MyOtherCaseClass
= MyOtherCaseClass
{ __id :: Int
, _name :: Text
}
class MyShow a where
myShow :: a -> String
instance MyShow Int where
myShow x = "int " ++ show x
instance MyShow Text where
myShow x = "a string " ++ show x
instance MyShow a => MyShow (Maybe a) where
myShow x =
case x of
Just y -> "Some " ++ myShow y
Nothing -> "Nothing"
instance (MyShow a, MyShow b) => MyShow (Either a b) where
myShow x =
case x of
Left l -> "left " ++ myShow l
Right r -> "right " ++ myShow r
instance MyShow MyCaseClass where
myShow (MyCaseClass _id name) =
myShow _id ++ " " ++ myShow name
main = do
putStrLn $ myShow $ (233 :: Int)
putStrLn $ myShow $ pack "Hello"
putStrLn $ myShow $ Just (223 :: Int)
putStrLn $ myShow $ Just $ pack "hello"
putStrLn $ myShow $ (Right (83 :: Int) :: Either Int Int)
putStrLn $ myShow $ MyCaseClass { _id = 1, name = (pack "eric") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment