首页 > 解决方案 > How to "zoom" through multiple levels of Maybe without getting nested Maybes?

问题描述

Let's have

data B = B {_b :: Maybe Int} deriving (Eq, Show, Generic)
makeFieldsNoPrefix ''B

data A = A {_a :: Maybe B} deriving (Eq, Show, Generic)
makeFieldsNoPrefix ''A

and now I want to "zoom" onto b from A (Maybe Int in Maybe B). I came up with:

let _TEST :: Maybe Int = (A {_a = Just B{_b = Just 7}}) ^. a ^? _Just . b & join

Is it possible to directly get Maybe Int using some lens operator without unpacking it with join from Maybe (Maybe Int)?

标签: haskellhaskell-lens

解决方案


_TEST ^? a . _Just . b . _Just


推荐阅读