在Haskell中,泛型编程通常通过类型类和多态函数来实现。下面是一个简单的例子:
-- 定义一个类型类class MyGeneric a where myGenericFunction :: a -> String-- 定义一个多态函数实例instance MyGeneric Int where myGenericFunction x = "This is an Int: " ++ show xinstance MyGeneric Char where myGenericFunction x = "This is a Char: " ++ [x]-- 使用多态函数main = do putStrLn $ myGenericFunction (5 :: Int) putStrLn $ myGenericFunction 'a'在这个例子中,我们定义了一个类型类MyGeneric,并为Int和Char类型实现了MyGeneric类型类的实例。接着我们定义了一个myGenericFunction函数,根据传入的类型不同,返回不同的字符串。最后在main函数中使用了myGenericFunction函数。这样就实现了简单的泛型编程。




