如何使用转换类型类
How to use conversion typeclasses
你好,我无法理解 typeclass
我需要用 Int
和 Double
进行数学运算(目前)。
data Numeric=I Int | D Double deriving (Show)
我希望能够在 I
和 D
上执行:+
、-
、*
、/
的,比较它们并订购它们。我需要实现哪个类型类? Num
,Integral
,Ord
?
您需要使 Num
的 class 实例具有 +
、-
、*
以及最重要的 fromInteger
和Fractional
的实例有 /
和 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)
你好,我无法理解 typeclass
我需要用 Int
和 Double
进行数学运算(目前)。
data Numeric=I Int | D Double deriving (Show)
我希望能够在 I
和 D
上执行:+
、-
、*
、/
的,比较它们并订购它们。我需要实现哪个类型类? Num
,Integral
,Ord
?
您需要使 Num
的 class 实例具有 +
、-
、*
以及最重要的 fromInteger
和Fractional
的实例有 /
和 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)