函数参数的Haskell模式匹配

时间:2015-07-17 19:51:17

标签: function haskell types pattern-matching

模式匹配是否不允许类型匹配,如 以下示例?

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"

1 个答案:

答案 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]