9 people like it.

Computation Builder for Cartesian Products

Sample framework for computing Cartesian products using a computation builder.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
// Computation expression for 
// Cartesian products.
// I use lists here, but any type with
// aggregate operations will work 
// (e.g. sequences).
// Notice how tiny it would be without
// all these comments and formatting -- 
// just three lines of code!
type Product () =

  member this.Bind (l,f) =
    // Collect lets you capture the result
    // in a list, but other operations 
    // are possible.  For example, map 
    // builds a hierarchy, and iter will 
    // let you use the results without 
    // aggregating them (return must be 
    // modified as shown below).
    List.collect f l

  member this.Return n = 
    // For collect and map:
    [n]
    // For iter:
    //()


let enumeratedPizzas = 
  Product() {
    // I never met a pizza I didn't like.
    let! x = ["New York";"Chicago"]
    let! y = ["Pepperoni";"Sausage"]
    let! z = ["Cheese";"Double Cheese"]
    // I capture the results in a tuple,
    // but you can do whatever here,
    // depending on aggregation, etc.
    return x,y,z
  }
Multiple items
type Product =
  new : unit -> Product
  member Bind : l:'b list * f:('b -> 'c list) -> 'c list
  member Return : n:'a -> 'a list

Full name: Script.Product

--------------------
new : unit -> Product
val this : Product
member Product.Bind : l:'b list * f:('b -> 'c list) -> 'c list

Full name: Script.Product.Bind
val l : 'b list
val f : ('b -> 'c 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 collect : mapping:('T -> 'U list) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.collect
member Product.Return : n:'a -> 'a list

Full name: Script.Product.Return
val n : 'a
val enumeratedPizzas : (string * string * string) list

Full name: Script.enumeratedPizzas
val x : string
val y : string
val z : string
Raw view New version

More information

Link:http://fssnip.net/4L
Posted:5 years ago
Author:TechNeilogy
Tags: computation builder , cartesian