LoginSignup
2
2

More than 5 years have passed since last update.

lens(のMonadState演算子など)で自己に言及したい時はidを使う

Last updated at Posted at 2017-10-29

この記事はブログ版の引用です。

スタイルが崩れている等している場合は、ブログ版の方が見やすいかと思います。


まとめ

 lensにて。
例えばInt[Int]のような単一の状態を持つMonadStateの文脈で、
状態自身(自己)に言及したい場合は、このようにすることで実現できる。

import Control.Lens
import Control.Monad.State.Lazy (StateT, runStateT)

main :: IO ()
main = runStateT context [0] >>= print

-- dequeue behavior
context :: StateT [Int] IO ()
context = do
  id %= (10 <|)
  id %= (|> 20)
-- {output}
-- ((),[10,0,20])
infix 4 %=
(%=) :: MonadState s m => ASetter s s a b -> (a -> b) -> m ()
(%=) :: ASetter s s a b -> (a -> b) -> StateT s m ()
(%=) :: ASetter' s a -> (a -> a) -> StateT s m ()
(%=) :: ASetter' [Int] [Int] -> ([Int] -> [Int]) -> StateT [Int] IO ()

(<|) :: a -> Seq a -> Seq a
(|>) :: Seq a -> a -> Seq a

(10 <|) :: Seq a -> Seq a
(|> 20) :: Seq a -> Seq a

type ASetter' s a = ASetter s s a a
type ASetter s t a b = (a -> Identity b) -> s -> Identity t

id :: p s (f a) -> p s (f a)
id :: (s -> f a) -> s -> f a
id :: (s -> Identity a) -> s -> Identity a
id :: ASetter' s a
id :: ASetter' [Int] [Int]

-- なので

(id %=) :: ([Int] -> [Int]) -> StateT [Int] IO ()

 ちなみにControl.Lens.Equalitysimple :: Equality' a aの実定義はid

参考

Thanks

2
2
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
2
2