使用镜头数组索引如果两个数组和索引都在国 [英] Using lens for array indexing if both array and index are in State

查看:114
本文介绍了使用镜头数组索引如果两个数组和索引都在国的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,并在状态单子数组索引。

I have an array and an array index in a state monad. I can read idx using use and modify it using += and 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 = do
    idx += x
    ii <- use idx
    return ii

现在我想结合改编 IDX 来形成一个镜头改编[ IDX]

Now I want to combine arr and idx to form a lens to arr[idx]:

combo arr idx = undefined

bar x = do
    combo arr idx += x
    ii <- combo arr idx
    return ii

我怎样才能做到这一点?将code是 Data.Sequence

推荐答案

答案竟然是刚刚

combo arr idx f m = (arr . ix (m^.idx)) f m

由于指数可能会出界, IX 是一个称为部分镜头穿越。因此,拥有使用使用而不是使用

As the index may be out of bounds, ix is a partial lens called Traversal. So bar has to use uses instead of use:

foo x = do
    combo arr idx += x
    ii <- uses $ combo arr idx
    return ii

还有 II 含半幺群M =&GT;米诠释,由于偏袒而不是内部

如果返回原不安全行为内部需要的话可以通过更换恢复使用 unsafeUses遍历=(^?遍历)LT; $&GT;获得

If original unsafe behaviour of returning Int is needed it can be restored by replacing uses with unsafeUses traversal = (^?! traversal) <$> get

这篇关于使用镜头数组索引如果两个数组和索引都在国的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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