18

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:

> data Foo a = Foo {_arg1 :: Int, _arg2 :: [a]}

I would like to make the lenses for Foo using the makeLenses template. I would like to do this without needing to read through the entire set of Template-Haskell docs.

What incantation can I type in at the GHCi prompt to get this to work?

1 Answer 1

19

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
2
  • 4
    It is worth mentioning that the makeLenses call has to go in the same :{ block as the data declaration! That threw me for a loop until I figured it out.
    – kqr
    Mar 31, 2015 at 11:45
  • 2
    It's enough to have any statement in the :{ block together with makeLenses, (it does not have to be the AST declaration). As far as I understand, then ghci will expand the makeLenses as declaration list. If there is only one statement in :{ block, then it tries to expand it as expression, giving type mismatch error.
    – max630
    Apr 12, 2016 at 15:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.