如何从GHCi中的记录制作镜头 [英] How do I make lenses from a record in GHCi

查看:70
本文介绍了如何从GHCi中的记录制作镜头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想稍微玩一下Lens库.我已将其加载到GHCi中,并创建了带有适当下划线的记录数据类型:

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]}

我想使用makeLenses模板制作用于Foo的镜头.我想这样做,而无需阅读整个 Template-Haskell文档.

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.

我可以在GHCi提示符下键入什么咒语才能使它起作用?

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

推荐答案

在GHCi 7.8.3中进行了测试:

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
:}

(我相信:{ ... :}块对于makeLenses起作用是必需的).

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

让我们简要检查一下:

λ >> AChar 100 'f' ^. aid
100
λ >> AChar 100 'f' ^? cval
Just 'f'
λ >> AInt 101 0 ^? cval
Nothing

这篇关于如何从GHCi中的记录制作镜头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆