Roman Dibikhin
Roman Dibikhin

Reputation: 856

F#: Compose empty sequence without using Seq.empty

I write my own reimplementation of LINQ using F# (thanks to Jon Skeet for inspiration).

I use a trick to generate empty sequence:

let empty<'b> =
        seq {
            for n = 0 to -1 do
                yield Unchecked.defaultof<'b>
        }

printfn "%A" empty<int> // -> seq []

Is there any idiomatic approach to do this?

(Seq.empty is not useful, I'm just reimplementing it)

Upvotes: 2

Views: 682

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

The simplest implementation using sequence expressions I can think of is:

let empty() = seq { do () }

Or if you want a generic value rather than a function:

let empty<'T> : seq<'T> = seq { do () }

One would want to write just seq { } for a sequence expression that does not produce any values, but that's not syntactically valid and so we need to do something inside the sequence expression. Using do () is just a way to tell the compiler that this is a syntactically valid sequence expression that does not do anything (and does not produce any values) when evaluated.

Upvotes: 9

Related Questions