2

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)

3
  • why is Seq.empty not usefull while the seq builder is? Anyway you can always use an object-expression that returns an IEnumerable<'b> which returns empty IEnumerator<'b> s Commented Oct 19, 2015 at 13:33
  • also [] :> 'a seq or [||] :> 'a seq or anything similiar ;) Commented Oct 19, 2015 at 13:34
  • The canon way of doing it can be seen here Commented Oct 19, 2015 at 13:34

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.