1

我想定义一个事物的多个版本,但具有不同的类型,以增强我程序中的类型安全性。例如,我有几种类型的双变量值,我想成为它们的实例,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 

这也可能吗?

4

2 回答 2

2

为什么不把它们变成新类型Bivar呢?

instance (Num a, Num b) => Num (a, b) where
    (a, b) + (a', b') = (a+a', b+b')
    (a, b) * (a', b') = (a*a', b*b')
    (a, b) - (a', b') = (a-a', b-b')
    fromInteger i = (fromInteger i, fromInteger i)
    abs    (a, b) = (abs    a, abs    b)
    signum (a, b) = (signum a, signum b)

newtype Bivar t   = Bivar     (t     , t     ) deriving (Show, Eq, Num)
newtype BivarNode = BivarNode (Int   , Int   ) deriving (Show, Eq, Num)
newtype BivarVal  = BivarVal  (Double, Double) deriving (Show, Eq, Num)
newtype HBivarVal = HBivarVal (Double, Double) deriving (Show, Eq, Num)
于 2012-04-29T02:03:35.793 回答
1

是的,您可以定义辅助函数:

bivarVal = BivarVal . Bivar
hBivarVal = HBivarVal . Bivar
bivarNode = BivarNode . Bivar
于 2012-04-28T12:48:01.740 回答