我是Haskell的新手,想学习如何从Num类实现我的复数.
data Complex = Complex{x::Float, y::Float} deriving (Show)
instance Num Complex where
(Complex x1 y1) + (Complex x2 y2) = Complex(x1 + x2) (y1 + y2)
(Complex x1 y1) - (Complex x2 y2) = Complex(x1 - x2) (y1 - y2)
(Complex x1 y1) * (Complex x2 y2) = Complex(x1*x2 - y1*y2) (x1*y2 + x2*y2)
fromInteger n = Complex(fromInteger n) (fromInteger n)
signum (Complex x y) = Complex(signum x) (signum y)
abs (Complex x y) = Complex(abs x) (abs y)
Run Code Online (Sandbox Code Playgroud)
我的问题是如何使用
fromInteger n = Complex(fromInteger n) (fromInteger n)
Run Code Online (Sandbox Code Playgroud)
以下是fromInteger在GHCi 中使用该函数的两个示例:
?> fromInteger 5 :: Complex
Complex {x = 5.0, y = 5.0}
Run Code Online (Sandbox Code Playgroud)
?> :set -XTypeApplications
?> fromInteger @Complex 5
Complex {x = 5.0, y = 5.0}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我相信你有错误的实施.查看源代码,看看它是如何完成的base.它似乎应该被定义为:
fromInteger n = Complex (fromInteger n) 0
Run Code Online (Sandbox Code Playgroud)