:wave: do we have anything similar to this in opt...
# arrow
t
👋 do we have anything similar to this in optics?
Copy code
public fun <A> listPredicate(p: (A) -> Boolean): Optional<List<A>, A> = Optional(
      getOption = { it.firstOrNull(p).toOption() },
      set = { list, newHead ->
        val index = list.indexOfFirst(p)

        if (index != -1) list.take(index) + newHead + list.drop(index + 1) else list
      }
    )
s
Hey @thanh, Yes, there is something like this in Arrow Optics. https://arrow-kt.io/docs/optics/filterindex/ The docs seem.. a bit lacking 😅
Optics could really use some love…
t
Thanks @simon.vergauwen! I think what I need is a bit different than the example with
FilterIndex
I want to filter with the value of the item in the list, not with the index. Maybe I missed something here?
s
Oh, I see. It’s only updating the first encountered in the list?
t
yes, it is, and I think it should. Maybe we can make another version of it with type
Lens<List<A>, List<A>>
which can get/set/modify all satisfied items.
s
That wouldn’t work in a composition chain, right?
t
yeah, that probably wouldn't work. Just poped out on my head 😄
@simon.vergauwen the code above seems to works really well. Should I create a PR to add it to
optics
? Maybe I can do some research how Haskell Lens deals with this problem first.
s
Hey @Alejandro Serrano Mena, do you know if something like this exists in Optics? I’ve used indexed traversals before, but just like
FilterIndex
they’re defined over indices of the list.
The easiest way to figure out if it composes correctly with the rest of the library would be to follow the set of
OptionalLaws
from
arrow-optics-test
. Have you tried running those against this instance?
t
I haven't tried to test it with
Laws
yet, but I can try to tests with the Laws tomorrow. I used it in a project and did some tests and it composes well with other optics functions.
Hi @simon.vergauwen, I'm struggling a bit on how to use the
OptionalLaws
and how to run the tests. Maybe I'll just create a PR and you can correct me there.
s
Hey Thanh, if that works for you that’d be easiest I think.
❤️ 1
t
In the other note, I check Scala Monocle, it has this function: https://github.com/optics-dev/Monocle/blob/master/core/shared/src/main/scala/monocle/Optional.scala#L226 which solves a problem when we want to access to all items that satisfied a predicate in a list.
I don't see it in Arrow's optics now, I can create another PR for this as well
I'll submit a PR in the next few days.
s
I see, thanks @thanh. Yes, a PR would be amazing! I’m excited to add new functionality in Arrow Optics and to clean it up, but I don’t have the time.
I see it also exists in Haskell and is called
filtered
in Haskell
t
yeah, it also says that in the scala docs. also agree that
optics
can definitely use some loves.