Using a Lens to read multiple fields

前端 未结 2 1873
难免孤独
难免孤独 2020-12-15 05:12

Given the types

data Prisoner = P { _name   :: String
                  , _rank   :: Int
                  , _cereal :: Cereal }

data Cereal = C { _number           


        
2条回答
  •  無奈伤痛
    2020-12-15 06:03

    We can use the Applicative instance of the ReifiedGetter newtype from Control.Lens.Reified:

    runGetter $ (,) <$> Getter number <*> Getter mascot
    

    In general, the newtypes in Control.Lens.Reified offer a lot of very useful instances for getters and folds.

    Note#1: Notice that we are combining the lenses as getters, and getting a getter in return. You can't obtain a composite lens in this way, as there would be problems if their "focuses" overlap. What could be the proper setter behaviour in that case?

    Note#2: The alongside function lets you combine two lenses, getting a bona-fide lens that works on the two halves of a product. This is different form the previous case because we can be sure the lenses don't overlap. alongside comes in handy when your type is a tuple or has an isomorphism to a tuple.

提交回复
热议问题