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.
Asked
Active
Viewed 343 times
5

Koz Ross
- 3,040
- 2
- 24
- 44
-
1You can use the [`Traversal'`](https://hackage.haskell.org/package/lens-4.14/docs/Control-Lens-Type.html#t:Traversal-39-) returned by [`ix`](https://hackage.haskell.org/package/lens-4.14/docs/Control-Lens-At.html#v:ix), but just give it a type of [`Fold`](https://hackage.haskell.org/package/lens-4.14/docs/Control-Lens-Type.html#t:Fold). Folds are read-only traversals, in some sense. Of course this doesn't help you if the type is abstract and you can't write to it, because you won't be able to instantiate `Ixed`. – Benjamin Hodgson Sep 03 '16 at 23:09
1 Answers
3
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

Shersh
- 9,019
- 3
- 33
- 61