Skip to content

Instantly share code, notes, and snippets.

@nagat01
Created June 11, 2011 06:03
Show Gist options
  • Select an option

  • Save nagat01/1020312 to your computer and use it in GitHub Desktop.

Select an option

Save nagat01/1020312 to your computer and use it in GitHub Desktop.
F#: Cartesian product of Collections.I want to write pure sequence version of it.
(* Result
[[1; 3]; [1; 4]; [2; 3]; [2; 4]]
[[3; 1]; [4; 1]; [3; 2]; [4; 2]]
seq [[1; 3]; [1; 4]; [2; 3]; [2; 4]]
seq [[1; 3]; [1; 4]; [2; 3]; [2; 4]]
*)
(*
let rec cartesian5 (ls: seq<seq<'a>>) : seq<seq<'a>> = seq{..}
I couldn't make cartesian from sequence of sequence
below 4 examples are similar to my purpose but little different
*)
open System
let rec cartesian = function
| l::ls ->
let accs = cartesian ls
let rec f=function
| e::es -> List.map(fun acc->e::acc) accs @ f es
| [] -> []
f l
| [] -> [[]]
let cartesian2 = List.fold(fun accs l->List.collect(fun acc->List.map(fun e->e::acc)l)accs) [[]]
let rec cartesian3 ls=
seq{
match ls with
| [] -> yield []
| hd::tl ->
for h in hd do
for t in cartesian3 tl do
yield h::t
}
let rec cartesian4 (ls: seq<'a>list) : seq<'a list> = seq{
match ls with
| [] -> yield []
| hd::tl -> yield! Seq.collect(fun h-> Seq.map(fun t-> h::t)<|cartesian4 tl)hd }
cartesian [[1;2];[3;4]] |> printfn"%A"
cartesian2 [[1;2];[3;4]] |> printfn"%A"
cartesian3 [[1;2];[3;4]] |> printfn"%A"
cartesian4 [[1;2];[3;4]] |> printfn"%A"
Console.ReadKey()|>ignore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment