haskell - Storing an Enum type in an unboxed Vector -


suppose have this:

data colour = red | blue | green    deriving (eq, ord, enum, bounded, read, show) 

and want have unboxed vector of colours. cannot directly (because colour isn't instance of unbox), can't tell how write unbox instance colour. the documentation unbox doesn't seem how make instance of (or @ least, not in way understand).

one approach use data.vector.unboxed.deriving, uses template haskell define correct instances new types in terms of existing types unbox instances.

{-# language multiparamtypeclasses, typefamilies, templatehaskell #-} module enum   import qualified data.vector.unboxed 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)) 

of course wastes space in case because use 2 of 8 bits in word8.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -