Saving an Enum Type in unboxed Vector

Suppose I have something like this:

data Colour = Red | Blue | Green
   deriving (Eq, Ord, Enum, Bounded, Read, Show)

And I want to have unboxed Vectorof Colours. I obviously cannot do this directly (because it is Colournot an instance Unbox), but I also cannot say how I will write the instance Unboxfor Colour. The documentation for Unboxdoes not seem to talk about how you are making any of this instance (or at least not as I understand it).

+4
source share
1 answer

Data.Vector.Unboxed.Deriving, Haskell Unbox .

{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, TemplateHaskell #-}
module Enum where


import qualified Data.Vector.Unboxed as U
import Data.Vector.Generic.Base
import Data.Vector.Generic.Mutable
import Data.Vector.Unboxed.Deriving
import Data.Word



data Colour = Red | Blue | Green
   deriving (Eq, Ord, Enum, Bounded, Read, Show)

colourToWord8 :: Colour -> Word8
colourToWord8 c =
    case c of
      Red -> 0
      Blue -> 1
      Green -> 2

word8ToColour :: Word8 -> Colour
word8ToColour w =
    case w of
      0 -> Red
      1 -> Blue
      _ -> Green


derivingUnbox "Colour"
  [t| Colour -> Word8 |]
  [| colourToWord8 |]
  [| word8ToColour |]


test n = U.generate n (word8ToColour . fromIntegral . (`mod` 3))

, , 2 8 Word8.

+5

Source: https://habr.com/ru/post/1649381/


All Articles