gpt4 book ai didi

haskell - "Inheriting"包装类型的实例

转载 作者:行者123 更新时间:2023-12-04 06:19:26 26 4
gpt4 key购买 nike

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

import Data.Word
data RijndaelField = RF Word8

我要 RijndaelField “继承” Word8 Bits 的实例以最简单的方式:
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

有没有更短的方法来表达 RijndaelField 之间的关系?和 Word8 ?

最佳答案

如果您不需要 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}

我认为这很方便

关于haskell - "Inheriting"包装类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20481718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com