如何使用转换类型类

How to use conversion typeclasses

你好,我无法理解 typeclass 我需要用 IntDouble 进行数学运算(目前)。

data Numeric=I Int | D Double deriving (Show)

我希望能够在 ID 上执行:+-*/的,比较它们并订购它们。我需要实现哪个类型类? Num,Integral,Ord

您需要使 Num 的 class 实例具有 +-* 以及最重要的 fromIntegerFractional 的实例有 /fromRational.

这是简化版的小存根:

data Numeric = N Double
   deriving Show

instance Num Numeric where
   (*) (N a) (N b) = N (a * b) 
   (+) (N a) (N b) = N (a + b) 
   (-) (N a) (N b) = N (a - b) 
   abs (N a) = N $ abs a
   signum (N a) = N $ signum a
   fromInteger a = N $ fromInteger a

instance Fractional Numeric where
   fromRational d = N $ fromRational d
   (/) (N a) (N b) = N (a / b)