Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List multiplication

Tags:

f#

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]
like image 885
Tom Squires Avatar asked Nov 24 '11 17:11

Tom Squires


2 Answers

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.

like image 52
Tomas Petricek Avatar answered Oct 20 '22 17:10

Tomas Petricek


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.

like image 32
Mauricio Scheffer Avatar answered Oct 20 '22 19:10

Mauricio Scheffer