我想定义一个事物的多个版本,但具有不同的类型,以增强我程序中的类型安全性。例如,我有几种类型的双变量值,我想成为它们的实例,Num
但它们都应该是不同的类型。所以我所做的是用一个类型变量创建一个新类型,并在此基础上声明新类型。但是,我发现我现在必须一直使用这两个构造函数有点烦人。有没有办法解决?
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype Bivar t = Bivar (t,t) deriving (Show, Eq)
instance (Num t) => Num (Bivar t) where
(+) (Bivar (x1,y1)) (Bivar (x2,y2)) = Bivar (x1+x2, y1+y2)
(-) (Bivar (x1,y1)) (Bivar (x2,y2)) = Bivar (x1-x2, y1-y2)
(*) (Bivar (x1,y1)) (Bivar (x2,y2)) = Bivar (x1*x2, y1*y2)
abs (Bivar (x1,y1)) = Bivar (abs x1, abs y1)
fromInteger i = Bivar (fromInteger i, fromInteger i)
signum (Bivar (x1,y1)) = Bivar (signum x1, signum y1)
newtype BivarNode = BivarNode (Bivar Int) deriving (Show, Eq, Num)
newtype BivarVal = BivarVal (Bivar Double) deriving (Show, Eq, Num)
newtype HBivarVal = HBivarVal (Bivar Double) deriving (Show, Eq, Num)
-- This is annoying:
a1 = BivarVal (Bivar (1.0, 2.0))
a2 = HBivarVal (Bivar (1.0, 2.0))
b = BivarNode (Bivar (1,2))
-- is there a way so that I can write it this way?
aa1 = BivarVal (1.0, 2.0)
aa2 = HBivarVal (1.0, 2.0)
bb = BivarNode (1,2)
谢谢你!
编辑:
为了扩展原始问题,我还想在模式匹配中使用类型名称,类似于
myFunction :: HBivarVal -> Double
myFunction (HBivarVal (Bivar (x,y))) = x
这也可能吗?