How can I use Control.Lens to update the ith element of a list?

亡梦爱人 提交于 2019-12-05 01:25:12

You can't* turn (!!) into any lens-like thing other than a Getter -- but there's a function to do this sort of thing: ix, for accessing things at indices. It's actually a Traversal, not a Lens -- which, here, just means that it can fail (if the index is out of bounds) -- but as long as the index is in the list, it'll work.

There's another problem, though -- (^.) is also an operator that's used exclusively for getting values. It's incompatible with e.g. (%=), which takes a lens-like thing as its first argument. And: (%=) is for mapping a function over the existing value; if you just want to set, you can use (.=). So you probably want something like:

list . ix i . inner .= True

* There actually is a function that can do this -- it's called upon -- but it uses wonderful evil black magic and you shouldn't use it, at least not for this (and probably not for any real code).

Use element, which is a Traversal to the specified list element:

list . element i . inner %= True :: Outer -> Outer

If you want to get the list element you must do so using a Maybe since the list element might not be there:

myList :: Outer

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