arrow icon indicating copy to clipboard operation
arrow copied to clipboard

Issues in `Iterable.kt`

Open theycome opened this issue 7 months ago • 3 comments

Backwards behavior Functions such as unweave, crosswalk, crosswalkNull transform the original collection in a reverse order. Is this the intentional behavior?..

listOf(1, 2, 3).crosswalkNull{ it } // [3, 2, 1]

crosswalkNull Returning List? is superfluous since fold always starts with an empty list so it will always return non-nullable list. Could be replaced with

  public fun <A, B> Iterable<A>.crosswalkNull(f: (A) -> B?): List<B> = fold<A, List<B>>(emptyList()) { bs, a ->
    Ior.fromNullables(f(a), bs)?.fold(
      { listOf(it) },
      ::identity,
      { l, r -> listOf(l) + r },
    ) ?: emptyList()
  }

theycome avatar May 22 '25 18:05 theycome

I remember finding such issues before because we were using foldRight in a ton of places. This should definitely be rewritten as a buildList or a mutableListOf<B>.apply {}. In fact, is this not just mapNotNull? I'm not sure, but I think so?

kyay10 avatar May 22 '25 18:05 kyay10

Exactly crosswalkNull is a simple a.reversed().mapNotNull()

theycome avatar May 22 '25 18:05 theycome

And reverse transformation is a result of a typo in 3 functions unweave, crosswalk, crosswalkNull

{ l, r -> listOf(l) + r }

which should have been r + listOf(l)

theycome avatar May 22 '25 20:05 theycome

Fixed by #3701

serras avatar Aug 28 '25 19:08 serras