I want to implement a function called output
which is overloaded for a scalar and a list:
For a scalar
x
, it executesprint x
(output 3
should print3
)For a list
x
, it executesputStr . unlines . map show x
(output [1, 2, 3]
should print1\n2\n3
)
Currently, I have non-overloaded outputScalar
and outputList
, both of which work (playground):
module Main where
main :: IO ()
main = do
outputScalar 3
outputList [1, 2, 3]
outputScalar :: (Show a, Num a) => a -> IO ()
outputScalar = print
outputList :: (Show a, Num a) => [a] -> IO ()
outputList = putStr . unlines . map show
Now I'd like to group them together to the single output
function, using overloading. I tried the code below (playground), but it doesn't even compile.
module Main where
main :: IO ()
main = do
output 1
output [1, 2, 3]
class Show a => Output a where
output :: a -> IO ()
instance (Show a, Num a) => Output a where
output :: a -> IO ()
output = print
instance (Show a, Num a) => Output [a] where
output :: [a] -> IO ()
output = putStr . unlines . map show
How can I fix the code? Or is it impossible to do that in Haskell?