我应该用什么镜头来建立按索引的只读吸气剂? [英] What in lens should I use to build a read-only getter by index?

查看:73
本文介绍了我应该用什么镜头来建立按索引的只读吸气剂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型,其内部详细信息是隐藏的.我想提供一种可以在特定索引处读取上述类型元素的镜头,但可以对其进行修改.我的类型的Ixed实例似乎没有执行我想要的操作,因为它明确允许修改(尽管不允许插入或删除).我不确定是否要允许只读索引.

I have a type whose internal details are hidden. I want to provide some kind of lens that can read elements from said type at particular indexes, but not modify them. An Ixed instance for my type doesn't seem to do what I want, as it explicitly allows modifications (though not insertions or deletions). I'm not sure what I use if I want to allow read-only indexing.

推荐答案

如果要定义只读镜头,则应使用Getter类型.让我们首先考虑一个简单的例子.您可以使用^?ix函数按索引访问元素.

If you want to define read-only lens you should use Getter type. Let's first consider simple example. You can access element by index using ^? and ix functions.

λ: [1..] ^? ix 10
Just 11
λ: import qualified Data.Map as M
λ: M.empty ^? ix 'a'
Nothing
λ: M.singleton 'a' 3 ^? ix 'a'
Just 3

因此,这是如何使用标准镜头访问索引数据结构的一个示例.这些知识足以定义您自己的只读索引的getter,但我将给出扩展示例.

So it was an example of how you can use standard lenses to access indexed data structures. These knowledges should be enough to define your own readonly indexed getter but I'll give extended example.

{-# LANGUAGE RankNTypes      #-}
{-# LANGUAGE TemplateHaskell #-}

import Control.Lens

data MyData = MkData
    { _innerList  :: [Int]
    , _dummyField :: Double
    }

makeLenses ''MyData

indexedGetter :: Int -> Getter MyData (Maybe Int)
indexedGetter i = innerList . to (^? ix i)

现在在ghci中,您可以使用此吸气剂.

Now in ghci you can use this getter.

λ: let exampleData = MkData [2, 1, 3] 0.3 
λ: exampleData ^. indexedGetter 0
Just 2
λ: exampleData & indexedGetter 0 .~ Just 100

<interactive>:7:15:
    No instance for (Contravariant Identity)
      arising from a use of ‘indexedGetter’
    In the first argument of ‘(.~)’, namely ‘indexedGetter 0’
    In the second argument of ‘(&)’, namely
      ‘indexedGetter 0 .~ Just 100’
    In the expression: exampleData & indexedGetter 0 .~ Just 100

这篇关于我应该用什么镜头来建立按索引的只读吸气剂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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