Haskell 如何处理重载多态性? [英] How does Haskell handle overloading polymorphism?

查看:27
本文介绍了Haskell 如何处理重载多态性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Haskell 多态性的问题.

据我所知,有两种类型的多态性:

  1. 参数:不指定输入类型.

    例子:

     函数名 :: [a] ->一个

  2. 重载:作为命令式编程,即将不同的参数传递给同一个函数.

我的问题是:Haskell 如何处理重载?

解决方案

Haskell 中的重载是使用类型类完成的.例如,假设您要重载一个返回 Int 的函数 foo:

class Fooable a wherefoo :: a ->诠释实例 Fooable Int 在哪里富=身份证instance Fooable Bool where富 _ = 42

但是,它们比大多数语言中的重载机制更强大.例如,您可以重载返回类型:

class Barable a where酒吧 :: Int ->一个实例 Barable Int 在哪里条 x = x + 3实例 Barable Bool where条 x = x <10

有关更多示例,请查看 Haskell 中的预定义类型类.p>

I have a question about Haskell polymorphism.

As I've learned, there are two types of polymorphism:

  1. Parametric: where you do not specify the input type.

    Example:

     functionName :: [a] -> a
    

  2. Overloading: as imperative programming, i.e. passing different arguments to the same function.

My problem is: how does Haskell handle overloading?

解决方案

Overloading in Haskell is done using type classes. For example, let's say you want to overload a function foo that returns an Int:

class Fooable a where
    foo :: a -> Int

instance Fooable Int where
    foo = id

instance Fooable Bool where
    foo _ = 42

However, they are more powerful than the overloading mechanisms found in most languages. For example, you can overload on the return type:

class Barable a where
    bar :: Int -> a

instance Barable Int where
    bar x = x + 3

instance Barable Bool where
    bar x = x < 10

For more examples, have a look at the predefined type classes in Haskell.

这篇关于Haskell 如何处理重载多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆