[英]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.