繁体   English   中英

Haskell通用类型

[英]Haskell Generic Type

因此,我才刚刚开始学习Haskell,并且在此方面已经停留了很长时间。 所以我有一个函数,可以在偏移量为负(最小值为0)之后计算数字。 我设法使用显式显示的类型执行此功能。

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

但是,当我尝试将其更改为使用如下所示的泛型类型时,它总是给我一个错误。 我做错了吗?

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

我得到的错误:

* 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

通过添加Ord来解决它:

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

如您所见,您需要将类型类Ord作为约束添加到具有以下类型签名的类型a

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

这是因为Ord是具有比较运算符(>=)(>=)的类型类。

之所以使用Ord,是因为存在像Strings这样的元素不适用于Num?

不可以,因为String不是Num类型类的成员,所以原始声明已将其排除为a类型a可能候选者。 如前所述,您需要使用Ord来确保类型a具有可用的运算符(>=)

暂无
暂无

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

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