我對 haskell 很陌生,對 Eq 有疑問。
data Rat = Rat Integer Integer
normaliseRat :: Rat -> Rat
normaliseRat (Rat x y)
|x < 0 && y < 0 = Rat (-x) (-y)
|otherwise = Rat (x `div`(gcd x y)) (y `div` (gcd x y))
所以我有一個 func normaliseRat。我需要的是 Eq 和 Ord 的實體。當然,Rat 2 4 == Rat 1 2 應該是有效的。
感謝幫助
uj5u.com熱心網友回復:
Haskell 不支持函式多載。但是(==)不是函式;它被宣告為型別類方法,因此該方法的任何特定于型別的實作都必須在instance宣告中定義,如下所示:
instance Eq Rat where
(Rat x y) == (Rat n m) = x * m == y * n
(x/y == n/m相當于,在交叉乘法之后,x * m == y * n乘??法更有效并且沒有除法會引入的精度問題。)
這同樣適用于Ord,除非您可以選擇實施(<=)或compare。(給定其中任何一個,其他比較方法的默認定義將起作用。)
instance Ord Rat where
-- I leave fixing this to accommodate negative numbers
-- correctly as an exercise.
(Rat x y) <= (Rat n m) = (x * m) <= (y * n)
作為一個型別類方法,(==)實際上是一個完整的函式家族,由它所使用的型別索引。宣告的目的instance不是重新定義方法,而是向該系列添加一個新函式。
如果啟用TypeApplications擴展,則可以將(==)其視為從型別到函式的映射。
> :t (==)
(==) :: Eq a => a -> a -> Bool
> :t (==) @Int
(==) @Int :: Int -> Int -> Bool
如果沒有型別應用程式,Haskell 的型別檢查器會自動找出要使用的函式:
> (==) 'c' 'd'
False
> (==) 3 5
False
但你可以明確:
> (==) @Char 'c 'd'
False
> (==) @Char 3 5
<interactive>:9:12: error:
? No instance for (Num Char) arising from the literal ‘3’
? In the second argument of ‘(==)’, namely ‘3’
In the expression: (==) @Char 3 5
In an equation for ‘it’: it = (==) @Char 3 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536678.html
上一篇:如何在Haskell中查找檔案的行數?(如何洗掉回圈?)
下一篇:如何訪問中間件中的回應狀態?
