Tom Squires
Tom Squires

Reputation: 9286

List multiplication

Is there any built-in function that multiplies all elements of a list with another?

i.e

let xList = [1..30]

let yList = [1..30]

would give:

[(1,1),(1,2),(1,3)..ect]

Upvotes: 6

Views: 2061

Answers (2)

Mauricio Scheffer
Mauricio Scheffer

Reputation: 99720

I'm starting to sound like a salesman :), but FSharpx has a function List.lift2 that does that (parameterized by a function, similar to Haskell's liftM2).

So with FSharpx it's let prod = List.lift2 tuple2 xList yList

(tuple2 is a tuple constructor, also included in FSharpx)

EDIT: just in case, I'd like to point out that I'm not suggesting to get a dependency on FSharpx just for this... of course you could just use a list comprehension or even just define lift2 and tuple2 yourself, they're trivial:

let inline lift2 f (l1: _ list) (l2: _ list) = 
    [ for i in l1 do
        for j in l2 do
            yield f i j ]

let inline tuple2 a b = a,b

FSharpx has a lot of built-in goodies like this.

Upvotes: 8

Tomas Petricek
Tomas Petricek

Reputation: 243041

This is called a cross-product or Cartesian product of lists. The easiest way to construct it is to use sequnce expressions - you can simply iterate over the two lists and yield all pairs:

let prod = [ for x in xList do
               for y in yList do
                 yield x,y ]

If you want to use higher-order functions, then you can use List.collect:

xList |> List.collect (fun x -> 
    yList |> List.map (fun y -> x, y))

For every value x from the xList, the lambda function generates a new list (such as [(x,1); (x,2); ... (x, n)]). The List.collect function then concatenates all these generated lists.

Upvotes: 13

Related Questions