扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Haskell中的泛型编程怎么实现

扬州沐宇科技
2024-04-16 17:27:08
Haskell

在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函数。这样就实现了简单的泛型编程。

扫码添加客服微信