mapping list of different types implementing same function?
Posted
by sisif
on Stack Overflow
See other posts from Stack Overflow
or by sisif
Published on 2010-06-17T11:49:46Z
Indexed on
2010/06/17
11:53 UTC
Read the original article
Hit count: 220
I want to apply a function to every element in a list (map) but the elements may have different types but all implement the same function (here "putOut") like an interface. However I cannot create a list of this "interface" type (here "Outputable").
How do I map a list of different types implementing the same function?
main :: IO ()
main = do
map putOut lst
putStrLn "end"
where
lst :: [Outputable] -- ERROR: Class "Outputable" used as a type
lst = [(Out1 1),(Out2 1 2)]
class Outputable a where
putOut :: a -> IO ()
-- user defined:
data Out1 = Out1 Int deriving (Show)
data Out2 = Out2 Int deriving (Show)
instance Outputable Out1 where
putOut out1 = putStrLn $ show out1
instance Outputable Out2 where
putOut out2 = putStrLn $ show out2
I cannot define it this way:
data Out = Out1 Int | Out2 Int Int
putOut Out1 = ...
putOut Out2 = ...
because this is a library and users should be able to extend Out with their own types
© Stack Overflow or respective owner