I suggest we ...

Seq.transpose

It would be nice to have a function that transposes sequences:
[ [ 00; 01; 02;... ]; [ 10; 11; 12;... ]; [ 20; 21; 22;... ];... ]
to
[ [ 00; 10; 20;... ]; [ 01; 11; 21;... ]; [02; 12; 22;... ];... ]

This is particularly useful when dealing with infinite x infinite sequences, where you want to iterate over the 'outer group' first.

14 votes
Vote
Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
You have left! (?) (thinking…)
James Ashwell shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

2 comments

Sign in
(thinking…)
Sign in with: facebook google
Signed in as (Sign out)
Submitting...
  • Reed Adams commented  ·   ·  Flag as inappropriate

    I'm quite the sucker for code golf. My solution:

    // implementation:
    let transposeInfinite seqs = Seq.initInfinite(fun i -> seqs |> Seq.map (Seq.item i))

    // verify:

    // (inf x inf) set, each starting 10 off
    let orig = Seq.initInfinite(fun i -> Seq.initInfinite((+) (i * 10)))

    printfn "orig: %A\n\ntrans: %A" orig (transposeInfinite orig)

  • Yaar Hever commented  ·   ·  Flag as inappropriate

    I took a stab at an implementation:

    module Seq =
    (**)
    (**)let transpose s =
    (****)seq {
    (******)let cachedOuter =
    (********)s |> Seq.map (fun inner -> (Seq.cast inner).GetEnumerator())
    (**********)|> Seq.cache
    (**)
    (******)let firstInner = Seq.head cachedOuter
    (**)
    (******)while firstInner.MoveNext() do
    (********)yield seq {
    (**********)yield firstInner.Current
    (**********)yield! cachedOuter
    (*****************)|> Seq.skip 1
    (*****************)|> Seq.map (fun inner ->
    (**********************)inner.MoveNext() |> ignore
    (**********************)inner.Current) } }

F# Language

Feedback and Knowledge Base