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

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

问题描述

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



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


  1. 参数:您不指定输入类型。 / p>

      functionName :: [a]  - >一个


  2. 重载:作为命令式编程,




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

    解决方案

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

      class Fooable a where 
    foo :: a - > Int

    实例Fooable Int其中
    foo = id

    实例Fooable Bool其中
    foo _ = 42

    然而,它们比大多数语言中的重载机制更强大。例如,你可以在返回类型上重载:

      class Barable a where 
    bar :: Int - > a

    实例Barable Int其中
    bar x = x + 3

    实例Barable Bool其中
    bar x = x < 10

    有关更多示例,请查看预定义的类型在Haskell中。


    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天全站免登陆