Last active
August 17, 2022 19:16
-
-
Save alekrutkowski/1216df7c9c8fca45b9ac01a711b73045 to your computer and use it in GitHub Desktop.
Multiple dispatch (double dispatch) in Haskell
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
main = do | |
putStrLn $ show $ add (MyInt 1) (MyInt 3) | |
-- MyInt 4 | |
putStrLn $ show $ add (MyInt 13) (MyString "B") | |
-- MyString "13B" | |
putStrLn $ show $ add (MyString "B") (MyInt 13) | |
-- MyString "B13" | |
putStrLn $ show $ add (MyString "a") (MyString "b") | |
-- MyString "ab" | |
putStrLn $ show $ add' $ IntInt 1 3 | |
-- MyInt'' 4 | |
putStrLn $ show $ add' $ IntString 13 "B" | |
-- MyString'' "13B" | |
putStrLn $ show $ add' $ StringInt "B" 13 | |
-- MySring'' "B13" | |
putStrLn $ show $ add' $ StringString "a" "b" | |
-- MyString'' "ab" | |
-- version 1 | |
data MyObj = MyInt Int | MyString String | |
deriving Show | |
add :: MyObj -> MyObj -> MyObj | |
add x y = | |
case (x, y) of | |
(MyInt a, MyInt b) -> MyInt $ a + b | |
(MyInt a, MyString b) -> MyString $ show a ++ b | |
(MyString a, MyInt b) -> MyString $ a ++ show b | |
(MyString a, MyString b) -> MyString $ a ++ b | |
-- version 2 | |
data MyObj' = | |
IntInt Int Int | | |
IntString Int String | | |
StringInt String Int | | |
StringString String String | |
data MyObj'' = MyInt'' Int | MyString'' String | |
deriving Show | |
add' :: MyObj' -> MyObj'' | |
add' x = | |
case x of | |
IntInt a b -> MyInt'' $ a + b | |
IntString a b -> MyString'' $ show a ++ b | |
StringInt a b -> MyString'' $ a ++ show b | |
StringString a b -> MyString'' $ a ++ b |
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
-- version 3 | |
-- inspired by https://stackoverflow.com/a/26305824 | |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} | |
module Main where | |
main = do | |
putStrLn $ show (add (1 :: Integer) (3 :: Integer) :: Integer) | |
-- 4 | |
putStrLn $ show (add (13 :: Integer) ("B" :: String) :: String) | |
-- "13B" | |
putStrLn $ show (add ("B" :: String) (13 :: Integer) :: String) | |
-- "B13" | |
putStrLn $ show (add ("a" :: String) ("b" :: String) :: String) | |
-- "ab" | |
class Adder a b c where | |
add :: a -> b -> c | |
instance Adder Integer Integer Integer where | |
add = (+) | |
instance Adder Integer String String where | |
add a b = show a ++ b | |
instance Adder String Integer String where | |
add a b = a ++ show b | |
instance Adder String String String where | |
add a b = a ++ b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment