“继承”包装类型的实例

时间:2013-12-09 22:00:04

标签: haskell typeclass

我的类型基本上充当另一种数据类型的标记:

import Data.Word
data RijndaelField = RF Word8

我希望RijndaelField以最简单的方式“继承”Word8 Bits {@ 1}}实例:

import Data.Bits
instance Bits RijndaelField where
    RF a .&. RF b     = RF $ a .&. b
    RF a .|. RF b     = RF $ a .|. b
    RF a `xor` RF b   = RF $ a `xor` b
    complement (RF a) = RF $ complement a
    shift (RF a) n    = RF $ shift a n
    rotate (RF a) n   = RF $ rotate a n
    bitSize (RF a)    = bitSize a
    isSigned (RF a)   = isSigned a
    testBit (RF a) n  = testBit a n
    bit n             = RF $ bit n
    popCount (RF a)   = popCount a

表示RijndaelFieldWord8之间的关系是否有更短的方法?

1 个答案:

答案 0 :(得分:12)

如果您不需要ADT或记录类型,则可以使用newtype代替GeneralizedNewtypeDeriving

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Data.Bits
import Data.Word

newtype RF = RF { unRF :: Word8 } deriving (Eq, Bits)

如果你真的想,你可以包括很多其他课程

newtype RF = RF { unRF :: Word8 }
    deriving (Eq, Bits, Num, Integral, Real, Enum, Ord, Show)

哪个可以让你用它

> 1 :: RF
RF {unRF = 1}
> [1..5] :: [RF]
[RF {unRF = 1},RF {unRF = 2},RF {unRF = 3},RF {unRF = 4},RF {unRF = 5}]
> let x = RF 1
> x + 2
RF {unRF = 3}

我觉得它很方便