How do I make lenses from a record in GHCi

后端 未结 1 677
[愿得一人]
[愿得一人] 2021-02-18 22:32

I want to play around with the Lens library a bit. I\'ve loaded it into GHCi and created a record data type with the appropriate underscores:

>          


        
相关标签:
1条回答
  • 2021-02-18 23:34

    Tested in GHCi 7.8.3:

    :set -XTemplateHaskell
    :m +Control.Lens
    :{
    data AST = AInt  { _aid :: Int, _ival :: Int }
             | AChar { _aid :: Int, _cval :: Char }
             deriving (Show)
    makeLenses ''AST
    :}
    

    (I believe that the :{ ... :} block is necessary for makeLenses to work).

    Let's briefly check:

    λ >> AChar 100 'f' ^. aid
    100
    λ >> AChar 100 'f' ^? cval
    Just 'f'
    λ >> AInt 101 0 ^? cval
    Nothing
    
    0 讨论(0)
提交回复
热议问题