Messing around with 'extension functions' for the List module.
(I spent quite a while developing 'mapfold' - which threads an accumulator like fold, but uses it as a parameter to create new values like map - then discovered that that is what List.scan_left
does)
For generation of test data, I needed to do a cross product of two lists, This is what I came up with:
///Perform cross product of two lists, return tuple
let crossproduct l1 l2 =
let product lst v2 = List.map (fun v1 -> (v1, v2)) lst
List.map_concat (product l1) l2
Is this any good, or is there already some better way to do this?
Same question for this one:
///Perform cross product of three lists, return tuple
let crossproduct3 l1 l2 l3 =
let tuplelist = crossproduct l1 l2 //not sure this is the best way...
let product3 lst2 v3 = List.map (fun (v1, v2) -> (v1, v2, v3)) lst2
List.map_concat (product3 tuplelist) l3
As we know if two lists are like (a, b) and (c, d) then the Cartesian product will be {(a, c), (a, d), (b, c), (b, d)}. To do this we shall use itertools library and use the product() function present in this library. The returned value of this function is an iterator.
To compute the cross product of two vectors, use the numpy. cross() method in Python Numpy. The method returns c, the Vector cross product(s).
The Cartesian product is the set of all combinations of elements from multiple sets.
The cartesian product of two sets will be a set of all possible ordered pairs with the first element of each ordered pair from the first set and the second element from the second set. We can find the cartesian product of sets saved as a 2D list using the following methods in Python.
another option is to use F# "sequence expressions" and write something like this:
let crossproduct l1 l2 =
seq { for el1 in l1 do
for el2 in l2 do
yield el1, el2 };;
(actually, it is almost the same thing as what you wrote, because 'for .. in .. do' in sequence expression can be viewed as map_concat). This works with (lazy) sequences, but if you want to work with lists, you'd just wrap the code inside [ ... ] rather than inside seq { ... }.
As of F# 4.0, you can use List.allPairs
to give the Cartesian product of two lists.
If you have more than two lists, see How do I compute the cartesian product of n sequences in F#?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With