LoginSignup
3
3

More than 5 years have passed since last update.

ADTをUnboxed Vectorにして、Lens経由でアクセスする

Posted at
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes           #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}

import           Control.Lens
import           Data.Vector.Generic.Lens
import qualified Data.Vector.Unboxed          as VU
import           Data.Vector.Unboxed.Deriving

data FluidCell a
  = FluidCell
    { _mass   :: !a
    , _energy :: !a
    , _volume :: !a
    }
    deriving (Eq, Show)

makeLenses ''FluidCell

derivingUnbox "FluidCell"
  [t| VU.Unbox a => FluidCell a -> (a, a, a) |]
  [e| \(FluidCell x y z) -> (x, y, z) |]
  [e| \(x, y, z) -> FluidCell x y z |]

main :: IO ()
main = do
  let v = VU.fromList [FluidCell (1 :: Int) 2 3, FluidCell 4 5 6] :: VU.Vector (FluidCell Int)
  print v
  -- > fromList [FluidCell {_mass = 1, _energy = 2, _volume = 3},FluidCell {_mass = 4, _energy = 5, _volume = 6}]
  print $ v ^._head . mass
  -- > 1
  print $ _head . mass .~ 9 $ v
  -- > fromList [FluidCell {_mass = 9, _energy = 2, _volume = 3},FluidCell {_mass = 4, _energy = 5, _volume = 6}]
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3