-- | Gray code is a binary numeral system where two successive numbers-- differ in only one bit.---- This module provides an interface to encode/decode @'Bits'@ types.---- Algorithm:-- Haupt, R.L. and Haupt, S.E., Practical Genetic Algorithms,-- Second ed. (2004), 5.4. Gray Codes.moduleCodec.Binary.Gray.Bits(gray,binary,showBits)whereimportData.Bits(Bits,testBit,setBit,clearBit,bitSize,shiftL,shiftR,complement,xor,(.&.),(.|.),isSigned)importqualifiedCodec.Binary.Gray.ListasL-- | Right shift without extension of the sign bit (reset it to zero).shiftR'::(Bitsa)=>a->Int->ashiftR'n0=nshiftR'ns|isSignedn&&signumn==-1=letn'=clearBit(shiftRn1)(bitSizen-1)inshiftR'n'(s-1)|otherwise=shiftRns-- | Convert an integer number from binary to Gray code.-- -- 'gray' is undefined for negative numbers of types that do not have-- fixed bitsize, e.g. for negative 'Integer's.gray::(Bitsa)=>a->agrayn=n`xor`(shiftR'n1)-- | Convert an integer number from Gray code to binary.-- -- 'binary' is undefined for types that do not have fixed bitsize,-- e.g. for 'Integer'.binary::(Bitsa)=>a->abinary0=0binaryn=binary'mask0n(copyMSBn)wheresz=bitSizen-1mask0=letm=setBit0szin(m,m)copyMSBn=(setBit0sz).&.nbinary'(maskReady,maskLast)ngraynbin|complementmaskReady==0=nbin|otherwise=letsz=bitSizengray-1nReady=maskReady.&.nbinmaskReady'=setBit(shiftRmaskReady1)szmaskLast'=shiftR'maskLast1nNext=(shiftR'(maskLast.&.nReady)1)`xor`(maskLast'.&.ngray)inbinary'(maskReady',maskLast')ngray(nReady.|.nNext)-- | Render binary code as a string of @0@s and @1@s.-- For example, @(42::Int8)@ is formatted as @101010@.showBits::(Bitsa)=>a->StringshowBits=L.showBits.L.toList