a wandering wolf

Does a wandering wolf dreams of a wondering, sometimes programming sheep?

このエントリーをはてなブックマークに追加

Add an element into a sequence

I wanted to add a element into a sequence, seq<’T> in F# and IEnumerable<T> in .NET, but I didn’t find any functions in Microsoft.FSharp.Collections.Seq module. And then, a good advice was brought to me:

It seemed very nice, so I tried it right away.

// a sequence under test
let ns = seq [1 .. 10]

// a helper function to print a sequence
let printSeq xs = xs |> Seq.toList |> printfn "%A"

// prepend an element to the sequence
seq {
  yield 0
  yield! ns
} |> printSeq
//> [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

// append an element to the sequence
seq {
  yield! ns
  yield 11
} |> printSeq
//> [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11]

Excellent! The code above is working well.

Because of no source evaluation, we can use it without the troubles of related to infinity sequences.