List multiplication

Is there a built-in function like List.zip that multiplies all list items by another?

ie

 let xList = [1..30] let yList = [1..30] 

will give:

 [(1,1),(1,2),(1,3)..ect] 
+4
source share
2 answers

This is called a cross product or a Cartesian product of lists. The easiest way to build this is to use sequnce expressions - you can just iterate over two lists and output all the pairs:

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

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

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

For each x value from xList , the lambda function generates a new list (for example, [(x,1); (x,2); ... (x, n)] ). The List.collect function List.collect combines all of these generated lists.

+12
source

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

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

( tuple2 is a tuple constructor also included in FSharpx)

EDIT: just in case, I would like to point out that I do not propose to get FSharpx dependency just for this ... of course, you could just use list comprehension or even just define lift2 and tuple2 yourself, they are trivial:

 let inline lift2 f (l1: _ list) (l2: _ list) = [ for i in l1 do for j in l2 do yield fij ] let inline tuple2 ab = a,b 

FSharpx has many built-in goodies like this one.

+8
source

Source: https://habr.com/ru/post/1382935/


All Articles