简体   繁体   English

Haskell通用类型

[英]Haskell Generic Type

So I just started learning Haskell and I have been stuck on this for quite some time already. 因此,我才刚刚开始学习Haskell,并且在此方面已经停留了很长时间。 So I have a function that calculates a number after an offset has been minus (minimum value is 0). 所以我有一个函数,可以在偏移量为负(最小值为0)之后计算数字。 I managed to do this function with the types explicitly shown. 我设法使用显式显示的类型执行此功能。

offSetter :: Int -> Int -> Int
offSetter number offset
    | number - offset >= 0 = number - offset
    | otherwise = 0

But when I tried to change it to use generic types as below, it keeps giving me an error. 但是,当我尝试将其更改为使用如下所示的泛型类型时,它总是给我一个错误。 Am I doing it wrong? 我做错了吗?

offSetter :: Num a => a -> a -> a
offSetter number offset
    | number - offset >= 0 = number - offset
    | otherwise = 0

The error I'm getting: 我得到的错误:

* Could not deduce (Ord a) arising from a use of '>='
      from the context: Num a
        bound by the type signature for:
                   offSetter :: forall a. Num a => a -> a -> a
        at src\test.hs:57:1-33
      Possible fix:
        add (Ord a) to the context of
          the type signature for:
            offSetter :: forall a. Num a => a -> a -> a
    * In the expression: number - offset >= 0
      In a stmt of a pattern guard for
                     an equation for `offSetter':
        number - offset >= 0

Solved it by adding Ord a: 通过添加Ord来解决它:

offSetter :: (Num a, Ord a) => a -> a -> a
offSetter number1 offSet
    | number1 - offSet >= 0 = number1 - offSet
    | otherwise = 0

As you discovered, you need to add the type class Ord as a constraint to the type a with the following type signature: 如您所见,您需要将类型类Ord作为约束添加到具有以下类型签名的类型a

offSetter :: (Num a, Ord a) => a -> a -> a

This is because Ord is the typeclass with comparison operators like (>=) . 这是因为Ord是具有比较运算符(>=)(>=)的类型类。

So Ord is used because there are elements like Strings that is not applicable to Num? 之所以使用Ord,是因为存在像Strings这样的元素不适用于Num?

No, since String is not a member of the Num typeclass, the original declaration already excludes it as a possible candidate for the type a . 不可以,因为String不是Num类型类的成员,所以原始声明已将其排除为a类型a可能候选者。 As I stated earlier, you need to use Ord in order to guarantee that the type a has the operator (>=) available. 如前所述,您需要使用Ord来确保类型a具有可用的运算符(>=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM