-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add zipWith
to NonEmptyList
#1870
Comments
After trying to generalize and optimize for some time, I came to the conclusion that the simplest solution is this: def zipWith[B, C](nel: NonEmptyList[B])(f: (A, B) => C): NonEmptyList[C] =
NonEmptyList.fromListUnsafe((nelA.toList, nelB.toList).zipped.map(f)) It's possible to zip two |
There's also this: def zipWith[F[_]: Traverse, A, B, C](fa: F[A], fb: F[B])(f: (A, Option[B]) => C): F[C] But I'm not sure if I like it. I'd probably prefer to define on NEL and NEV individually. |
I think the issue here with being generic is that For now, the zipWith on NonEmptyList, what about: def zipWith[B, C](that: NonEmptyList[B])(f: (A, B) => C): NonEmptyList[C] = {
def zwRev(as: List[A], bs: List[B], acc: List[C]): List[C] = {
case (Nil, _) => acc
case (_, Nil) => acc
case (a :: as, b :: bs) => zwRev(as, bs, f(a, b) :: acc)
}
NonEmptyList(f(this.head, that.head), zwRev(this.tail, that.tail, Nil).reverse)
} in this way we avoid the double allocations of Worth it for library code that will be used over and over. |
|
Did a quick benchmark with sbt-jmh, here are the results for zipping 100k elements :) NonEmptyList:
NonEmptyVector:
Not super surprising, since pattern matching on Vectors is pretty inefficient. But good to know your algorithm is faster than the standard library for NELs ;) PR including tests to follow! |
pretty sad that the naive functional zipWith is faster than the standard library. thanks for tacking this so well (benchmarks, great PR)! |
There's currently no way to zip two (or more) NELs, I think it is a very common use case and would be a worthwhile addition. We could even maybe generalize it to
Reducible
. Will have to look into that. What do you think?The text was updated successfully, but these errors were encountered: