JORGE
JORGE

Reputation: 167

Haskell list of lists multiplication

If I have 2 lists of lists in Haskell like the following:

[[1,1,1],[3,4,6],[1,2,3]] [[3,2,2],[3,4,5],[5,4,3]]

I must multiply the first lists, second lists, and so on.

The example above should result in

[[3,2,2],[9,16,30],[5,8,9]]

This is what I have done:

multListt xss yss = [zipWith (*) xs ys | xs <- xss, ys <- yss]

My result is:

[[3,2,2],[3,4,5],[5,4,3],[9,8,12],[9,16,30],[15,16,18],[3,4,6],[3,8,15],
[5,8,9]]

This means that my process takes 1 element of first list and multiplies it by all of the elements in list 2, and so on.

Can you please provide a clue to solve my issue?

Respectfully,
Jorge Maldonado

Upvotes: 0

Views: 1138

Answers (2)

redneb
redneb

Reputation: 23850

You can do using two nested calls to zipWith like this:

zipWith (zipWith (*)) [[1,1,1],[3,4,6],[1,2,3]] [[3,2,2],[3,4,5],[5,4,3]]

Or can use parallalel list comprehensions like that:

[zipWith (*) xs ys | xs <- [[1,1,1],[3,4,6],[1,2,3]] | ys <- [[3,2,2],[3,4,5],[5,4,3]]]

The last solution requires the ParallelListComp language extension.

Upvotes: 3

Sophie Swett
Sophie Swett

Reputation: 3390

Use zipWith twice.

multListt xss yss = zipWith (zipWith (*)) xss yss

Upvotes: 6

Related Questions