49 people like it.

Cartesian Product of Lists

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

 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 list of lists.
let rec cartList nll = 
  let f0 n nll =  
    match nll with
    | [] -> [[n]]
    | _ -> List.map (fun nl->n::nl) nll
  match nll with
  | [] -> []
  | h::t -> List.collect (fun n->f0 n (cartList t)) h
 
 
// Test.

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

pizzas |> Seq.iter (printfn "%A")
val cartList : nll:'a list list -> 'a list list

Full name: Script.cartList
val nll : 'a list list
val f0 : ('b -> 'b list list -> 'b list list)
val n : 'b
val nll : 'b list list
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val map : mapping:('T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.map
val nl : 'b list
val h : 'a list
val t : 'a list list
val collect : mapping:('T -> 'U list) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.collect
val n : 'a
val choices : string list list

Full name: Script.choices
val pizzas : string list list

Full name: Script.pizzas
module Seq

from Microsoft.FSharp.Collections
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/1e
Posted:13 years ago
Author:Neil Carrier
Tags: cartesian product , list