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