Use the lens as a "card"

I want to convert this line of code map (^?! ix 0) [[0, 1], [4, 5], [9, 1]] to make full use of the lenses, so something like [[0, 1], [4, 5], [9, 1]] & each . ix 0 [[0, 1], [4, 5], [9, 1]] & each . ix 0 . However, the types do not match. What is the right way to do this?

+8
haskell lenses
source share
2 answers

Use folded :

 Prelude Control.Lens> [[0, 1], [4, 5], [9, 1]] ^.. folded . ix 0 [0,4,9] 

Works with any Foldable .

Also, if you plan on always fetching the first element, it might be easier to use the _head bypass from Control.Lens.Cons instead of ix .

 [[0, 1], [4, 5], [9, 1]] ^.. folded . _head 
+10
source share

You can use any of

 Prelude Control.Lens> [[0, 1], [4, 5], [9, 1]] & each %~ (^?! ix 0) [0,4,9] Prelude Control.Lens> [[0, 1], [4, 5], [9, 1]] ^.. each . ix 0 [0,4,9] 

The first corresponds exactly to what you wrote using the unsafe operator (^?!) , which means that it can give an error. Secondly, itโ€™s safer to leave empty lists.

They work in different ways: the first creates a modified version of the original structure, which is more consistent with what map does, and can be used for structures that are not lists.

The second creates a summary of your structure using a folded lens; although it can be used with many types of structures, the result is always a list.

You can also replace each with traverse (or, as @danidiaz points out, a little more general traversed ). The former works for many special things, such as tuples, and the latter works for any Traversable .

+10
source share

All Articles