Haskell中的泛型编程怎么实现

2024-04-16

在Haskell中,泛型编程通常通过类型类和多态函数来实现。下面是一个简单的例子:

-- 定义一个类型类
class MyGeneric a where
  myGenericFunction :: a -> String

-- 定义一个多态函数实例
instance MyGeneric Int where
  myGenericFunction x = "This is an Int: " ++ show x

instance MyGeneric Char where
  myGenericFunction x = "This is a Char: " ++ [x]

-- 使用多态函数
main = do
  putStrLn $ myGenericFunction (5 :: Int)
  putStrLn $ myGenericFunction 'a'

在这个例子中,我们定义了一个类型类MyGeneric,并为IntChar类型实现了MyGeneric类型类的实例。接着我们定义了一个myGenericFunction函数,根据传入的类型不同,返回不同的字符串。最后在main函数中使用了myGenericFunction函数。这样就实现了简单的泛型编程。

《Haskell中的泛型编程怎么实现.doc》

下载本文的Word格式文档,以方便收藏与打印。