LearnerX
LearnerX

Reputation: 137

Multiply a list and a list of lists

I'm trying to multiply the first element of list2 by every element of the first list in list1 and then multiply the second element of list2 by every element of the second list in list1 and so on.

let list1 = [[5;6;7];[8;9;10];[11;12;13]]

let list2 = [2;3;4]

My desired output is [[10; 12; 14]; [24; 27; 30]; [44; 48; 52]]

I have tried

list1 |> List.map (List.map2 (*) list2)

Which produces [[10; 18; 28]; [16; 27; 40]; [22; 36; 52]]

Upvotes: 2

Views: 55

Answers (1)

Brian Berns
Brian Berns

Reputation: 17038

Here's a basic solution:

let multElem list elem =
    list |> List.map ((*) elem)

let mult list1 list2 =
    List.map2 multElem list1 list2

mult list1 list2

Upvotes: 3

Related Questions