Created
October 19, 2019 02:45
-
-
Save decapo01/c7cddc279db9126900c5e506b99c5358 to your computer and use it in GitHub Desktop.
Hasell show typeclass
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
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