- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Zip with side effect?
Tue, 2011-07-12, 16:42
Hello,
This is probably a stupid question, but I thought I should ask, since I search for quite
some time without success...
To apply a side effect to a list, we have foreach:
List("a", "b", "c").foreach(doSomething)
To conflate together two lists, we have zip:
List("a", "b", "c").zip(List(1, 2, 3))
Do we have a zip with side-effect, calling a method with a parameter from a list on each
element of a list?
Ie. given a list of Foo: List(foo1, foo2, foo3)
Given a function taking Foo and Bar parameters applying a Unit method from Foo with Bar:
(f: Foo, b: Bar) => Unit = { f.stuff(b) } // For example list.add(element) or
elt.setColor(c) or similar
Can we do something like:
List(foo1, foo2, foo3).zipEach(_.stuff(_), List(bar1, bar2, bar3))
or at least:
List(foo1, foo2, foo3).zipEach({(f: Foo, b: Bar) => f.stuff(b) }, List(bar1, bar2, bar3))
that would be equivalent to:
foo1.stuff(bar1)
foo2.stuff(bar2)
foo3.stuff(bar3)
?
Does it even make sense? (mixing functional style and side effect... although foreach is
here for that).
I am suspecting the powerful for comprehension can do the job, but I don't see how.
Tue, 2011-07-12, 17:27
#2
Re: Zip with side effect?
On 12/07/2011 17:52, Daniel Sobral wrote:
> (foo, bar).zip.foreach(doSomething)
Hey, it works! (almost, see below)
I suppose it was too obvious for me... :-)
For the record, I got a warning on using zip on a Tuple (I always compile with deprecation
warnings), so I used a zipped instead:
(shapes, color).zipped.foreach(_.setColor(_))
That's cool, thanks!
(foo, bar).zip.foreach(doSomething)
On Tue, Jul 12, 2011 at 12:42, Philippe Lhoste wrote:
> Hello,
>
> This is probably a stupid question, but I thought I should ask, since I
> search for quite some time without success...
>
> To apply a side effect to a list, we have foreach:
> List("a", "b", "c").foreach(doSomething)
>
> To conflate together two lists, we have zip:
> List("a", "b", "c").zip(List(1, 2, 3))
>
> Do we have a zip with side-effect, calling a method with a parameter from a
> list on each element of a list?
> Ie. given a list of Foo: List(foo1, foo2, foo3)
> Given a function taking Foo and Bar parameters applying a Unit method from
> Foo with Bar: (f: Foo, b: Bar) => Unit = { f.stuff(b) } // For example
> list.add(element) or elt.setColor(c) or similar
>
> Can we do something like:
> List(foo1, foo2, foo3).zipEach(_.stuff(_), List(bar1, bar2, bar3))
> or at least:
> List(foo1, foo2, foo3).zipEach({(f: Foo, b: Bar) => f.stuff(b) }, List(bar1,
> bar2, bar3))
> that would be equivalent to:
> foo1.stuff(bar1)
> foo2.stuff(bar2)
> foo3.stuff(bar3)
> ?
>
> Does it even make sense? (mixing functional style and side effect...
> although foreach is here for that).
>
> I am suspecting the powerful for comprehension can do the job, but I don't
> see how.
>
> --
> Philippe Lhoste