Lens
- A Little Lens Starter Tutorial
- Lensの前にHaskellの基礎(型, カリー化と部分適用, kindやるか?)
- getterとsetterをまとめたもの
- Optics の一種らしい?
- Lens は Iso の特殊化
Basic Lens(getter, setter)
{-# LANGUAGE Rank2Types #-}
-- Lens as a getter & updater
data Lens s a = Lens
{ get :: s -> a
, update :: (a -> a) -> s -> s
}
-- set :: Lens s a -> a -> s -> set
-- set l a s = update l (const a) s
compose :: Lens b c -> Lens a b -> Lens a c
compose bc ab = Lens
{ get = get bc . get ab
, update = update ab . update bc
}
fstL :: Lens (a, b) a
fstL = Lens
{ get = \(x, y) -> x
, update = \f (x, y) -> (f x, y)
}
sndL :: Lens (a, b) b
sndL = Lens
{ get = \(x, y) -> y
, update = \f (x, y) -> (x, f y)
}
main = do
print $ update fstL (+1) (1, 2)
print $ update (sndL `compose` fstL) (*2) ((3, 4), 5)-
CPS based: 継続渡しスタイル
-
rank1が多相関数→型パラメータが固定されてしまう
参考文献
- basic Lens と van Laarhoven lens が 圏同型 の視点で解説?