What in lens should I use to build a read-only getter by index?

流过昼夜 提交于 2019-12-12 12:12:23

问题


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.


回答1:


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

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)

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


来源:https://stackoverflow.com/questions/39311908/what-in-lens-should-i-use-to-build-a-read-only-getter-by-index

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