haskell - Using lens for array indexing if both array and index are in State -
i have array , array index in state monad. can read idx using use
, modify using +=
, other similar modifiers:
{-# language templatehaskell #-} import control.lens import control.lens.th import control.monad.state import data.array data m = m { _arr :: array int int, _idx :: int } $(makelenses ''m) foo x = idx += x ii <- use idx return ii
now want combine arr
, idx
form lens arr[idx]
:
combo arr idx = undefined bar x = combo arr idx += x ii <- combo arr idx return ii
how can this? code different data.sequence
?
the answer turned out just
combo arr idx f m = (arr . ix (m^.idx)) f m
as index may out of bounds, ix
partial lens called traversal
. bar
has use uses
instead of use
:
foo x = combo arr idx += x ii <- uses $ combo arr idx return ii
also ii
monoid m => m int
instead of int
, because of partiality.
if original unsafe behaviour of returning int
needed can restored replacing uses
unsafeuses traversal = (^?! traversal) <$> get
Comments
Post a Comment