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
Addition of #zipWith Method to Standard Collections #1512
Comments
Imported From: https://issues.scala-lang.org/browse/SI-1512?orig=1 |
@DRMacIver said: Maybe we can try to get a bunch of them in as part of the collections upgrade? |
@odersky said: |
@DRMacIver said: |
Anders Bach Nielsen [X] (nielsen) said: |
@paulp said: |
@odersky said: scala> val xs = List(1, 2, 3)
xs: List[Int] = List(1, 2, 3)
scala> (xs, xs).zipped map (_ + _)
res1: List[Int] = List(2, 4, 6) |
@SethTisue said: |
@djspiewak said:
How is this an improvement over: val xs = List(1, 2, 3)
xs zip xs map { _ + _ } In fact, it's actually longer. |
@SethTisue said: |
@djspiewak said: |
@odersky said: |
Several collections in the Scala library have a #zip method. This method takes another collection and then merges it with the invocation target, producing a collection of type (A, B), where A is the component type of
this
and B is the component type ofthat
.However, I do not believe that this method is general enough. It somewhat-arbitrarily decides that the best way to "merge" to collection elements is to wrap them together in a 2-tuple. This is fine for correctness, but most often the user of the API must take an extra step to "unwrap" these values in order to produce the desired result. This can be inefficient, and generally constitutes extra code which can obscure intent.
I would request the addition of a #zipWith method (patterned after Haskell's function of the same name) to every collection which supports #zip. At a minimum, this method could be defined in terms of #zip and #map:
This is sub-optimal because it traverses the collection twice and produces an intermediary "throw-away" value, but it is the simplest approach.
This method would be useful in a number of situations, including (but not limited to) everyone's favorite infinite series (assuming :: syntax for Streams):
More generally though, I think it would be a more concise and more readable method in just about every situation where #zip would be applied. Logically, #zip is just a specialization of #zipWith, passing a function which takes two values and returns a tuple of the same.
The text was updated successfully, but these errors were encountered: