码迷,mamicode.com
首页 > 编程语言 > 详细

Haskell语言学习笔记(64)Lens(4)

时间:2017-12-14 04:26:35      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:const   语言   https   学习笔记   链接   pos   down   string   str   

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)

标签:const   语言   https   学习笔记   链接   pos   down   string   str   

原文地址:http://www.cnblogs.com/zwvista/p/8035209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!