Elegant way to apply curried function to indexed traversal

52 Views Asked by At

I want to compose a curried function

f :: i -> a -> b

With an indexed traversal

l :: IndexedTraversal' i s a

apply it to an s and get back a [b].

I came up with

s ^.. l . withIndex . to (uncurry f)

But I would like a combinator itoListByOf that would allow me to do this

s & itoListByOf l f

Like

itoListByOf :: IndexedGetting i (Endo [b]) s a -> (i-> a -> b) -> s -> [b]
itoListByOf l f = ifoldrOf l (\i a -> (f i a :)) []

But I want to make sure I'm not missing this combinator hiding in the library with a more general type.

1

There are 1 best solutions below

1
hamza koyuer On BEST ANSWER

It looks like you have correctly defined the itoListByOf function to achieve your goal. While there are many combinators in the lens library that provide similar functionality, I don't think there is a more general combinator with exactly the type you are looking for.

The ifoldrOf function you use in your definition of itoListByOf is itself a very general function that can be used to traverse any IndexedFold and accumulate results. The itoListByOf function simply specializes ifoldrOf to the case where the accumulation function is a function that applies the f function to each element of the fold and appends the result to a list.

In summary, I believe your implementation of itoListByOf is a good one, and there is not a more general combinator with the same type in the lens library.