How do I make lenses from a record in GHCi

拥有回忆 提交于 2019-12-05 11:13:23

问题


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:


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


来源:https://stackoverflow.com/questions/18395816/how-do-i-make-lenses-from-a-record-in-ghci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!