问题
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