55 people like it.

Cartesian Product of Sequences

Computes the Cartesian product of a sequence of sequences. See corresponding example for a list of lists.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
// Cartesian product of a sequence of sequences.
let rec cartSeq (nss:seq<#seq<'a>>) = 
  let f0 (n:'a) (nss:seq<#seq<'a>>) = 
    match Seq.isEmpty nss with
    | true -> Seq.singleton(Seq.singleton n)
    | _ -> Seq.map (fun (nl:#seq<'a>)->seq{yield n; yield! nl}) nss
  match Seq.isEmpty nss with
  | true -> Seq.empty
  | _ -> Seq.collect (fun n->f0 n (cartSeq (Seq.skip 1 nss))) (Seq.head nss)
 
 
// Test.

let choices = 
  [
    ["crispy";"thick";"deep-dish";];
    ["pepperoni";"sausage";];
    ["onions";"peppers";];
    ["mozzarella";"provolone";"parmesan"];
  ] 
 
let pizzas = cartSeq choices

pizzas |> Seq.iter (printfn "%A")
val cartSeq : nss:seq<#seq<'a0>> -> seq<seq<'a0>>

Full name: Script.cartSeq
val nss : seq<#seq<'a0>>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val f0 : ('a -> seq<#seq<'a>> -> seq<seq<'a>>)
val n : 'a
val nss : seq<#seq<'a>>
module Seq

from Microsoft.FSharp.Collections
val isEmpty : source:seq<'T> -> bool

Full name: Microsoft.FSharp.Collections.Seq.isEmpty
val singleton : value:'T -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.singleton
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val nl : #seq<'a>
val empty<'T> : seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.empty
val collect : mapping:('T -> #seq<'U>) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.collect
val skip : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.skip
val head : source:seq<'T> -> 'T

Full name: Microsoft.FSharp.Collections.Seq.head
val choices : string list list

Full name: Script.choices
val pizzas : seq<seq<string>>

Full name: Script.pizzas
val iter : action:('T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view Test code New version

More information

Link:http://fssnip.net/1f
Posted:13 years ago
Author:Neil Carrier
Tags: cartesian product , seq