1. 程式人生 > >Haskell語言學習筆記(64)Lens(4)

Haskell語言學習筆記(64)Lens(4)

.cn str .com get prev blog int vista pri

Prisms

data NewTask =
  SimpleTask String |
  HarderTask String Int |
  CompoundTask String [NewTask]
  deriving (Show)

makePrisms ''NewTask
*Main> a ^? _SimpleTask
Just "Clean"
*Main> b ^? _HarderTask
Just ("Clean Kitchen",15)
*Main> b ^? _HarderTask._2
Just 15
*Main> b & _SimpleTask .~ "Clean Garage"
HarderTask "Clean Kitchen" 15
*Main> b & _HarderTask._2 .~ 30
HarderTask "Clean Kitchen" 30

手動計算

_Left = prism Left $ either Right (Left . Right)

prism bt seta = dimap seta (either pure (fmap bt)) . right'

data Market a b s t = Market (b -> t) (s -> Either t a)
instance Choice (Market a b) where
  right' (Market bt seta) = Market (Right . bt) $ \cs -> case cs of
    Left c -> Left (Left c)
    Right s -> case seta s of
      Left t -> Left (Right t)
      Right a -> Right a

preview l = getFirst . foldMapOf l (First . Just)

foldMapOf l f = getConst . l (Const . f)
Prelude Control.Lens> preview _Left (Left 5)
Just 5

參考鏈接

Haskell語言學習筆記(38)Lens(1)
Haskell語言學習筆記(44)Lens(2)
Haskell語言學習筆記(56)Lens(3)
Taking a Close look at Lenses

Haskell語言學習筆記(64)Lens(4)