How do I multiply two Lists?

1,978 views
Skip to first unread message

halheinrich

unread,
Dec 6, 2012, 11:40:09 AM12/6/12
to scala...@googlegroups.com
Given two lists:

val l1: List[Int] = List(1, 2, 3)
val l2: List[Int] = List(4, 5, 6)

What code will multiply those two together to arrive at:

val l3: List[Int] = List(4, 10, 18)

Thanks for any help!
Hal

Erik Osheim

unread,
Dec 6, 2012, 11:45:18 AM12/6/12
to halheinrich, scala...@googlegroups.com
On Thu, Dec 06, 2012 at 08:40:09AM -0800, halheinrich wrote:
> What code will multiply those two together to arrive at:
>
> val l3: List[Int] = List(4, 10, 18)

Consider:

val ns1 = 1 :: 2 :: 3 :: Nil
val ns2 = 2 :: 4 :: 6 :: Nil
ns1.zip(ns).map { case (a, b) => a * b }
// res0: List[Int] = List(2, 8, 18)

Hope this helps!

-- Erik

Johannes Rudolph

unread,
Dec 6, 2012, 11:45:10 AM12/6/12
to halheinrich, scala-user
On Thu, Dec 6, 2012 at 5:40 PM, halheinrich <halhe...@telusplanet.net> wrote:
> What code will multiply those two together to arrive at:

val l3 = (l1, l2).zipped.map(_ * _)


--
Johannes

-----------------------------------------------
Johannes Rudolph
http://virtual-void.net

Vlad Patryshev

unread,
Dec 6, 2012, 12:10:37 PM12/6/12
to halheinrich, scala...@googlegroups.com
From the applicative functors point of view, you are dealing with ziplists; so, the responses above are the solutions you need unless you  ause scalaz where these ops are supposed to be present (did not check).

There's a big question, if two lists have different sizes, what would you expect? The shortest?

Thanks,
-Vlad

Alec Zorab

unread,
Dec 6, 2012, 1:03:43 PM12/6/12
to Vlad Patryshev, halheinrich, scala-user
Scalaz 6 has zipstreams, so you can do this:

(zip(Stream(1,2,3)) |@| zip(Stream(3,4,5))) (_ + _)

Vlad Patryshev

unread,
Dec 6, 2012, 1:32:02 PM12/6/12
to Alec Zorab, halheinrich, scala-user
Right, it should be a stream of course.

Thanks,
-Vlad

halheinrich

unread,
Dec 6, 2012, 9:43:08 PM12/6/12
to scala...@googlegroups.com, halheinrich, er...@plastic-idolatry.com
That worked! Thanks for the help
Hal

halheinrich

unread,
Dec 6, 2012, 9:44:29 PM12/6/12
to scala...@googlegroups.com, halheinrich, johannes...@googlemail.com
That works! Thank you.
And this construct is more concise than the previous one.
 
Hal
Reply all
Reply to author
Forward
0 new messages