模式匹配是否不允许类型匹配,如 以下示例?
printit :: Int -> IO ()
printit i = print $ "Int i = " ++ show i
printit :: [Char] -> IO ()
printit s = print $ "[char] s = " ++ show s
main :: IO ()
main = do
printit 2
printit "two"
答案 0 :(得分:2)
类型类提供类似的东西:
class Printable a where printit :: a -> IO ()
instance Printable Int where printit i = print $ "Int i = " ++ show i
instance Printable [Char] where printit s = print $ "[char] s = " ++ show s
在两种实现中,您可能都需要putStrLn
而不是print
。您可能也喜欢Typeable
课程;一个人可以写
printWithType :: (Show a, Typeable a) => a -> IO ()
printWithType v = putStrLn $ show v ++ " :: " ++ show (typeOf v)
......表现得如此:
> printWithType 3
3 :: Integer
> printWithType "foo"
"foo" :: [Char]