Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an F# equivalent of Enumerable.DefaultIfEmpty?

Tags:

linq

f#

After searching quite a bit, I couldn't find an F# equivalent of Enumerable.DefaultIfEmpty.

Does something similar exists in F# (perhaps in a different, idiomatic, way)?

like image 308
Nikos Baxevanis Avatar asked Feb 04 '14 08:02

Nikos Baxevanis


1 Answers

To preserve the laziness of the sequence, we could work with the enumerator's state.

let DefaultIfEmpty (l:'t seq) (d:'t) = 
    seq{
        use en = l.GetEnumerator()
        if en.MoveNext() then 
            yield en.Current
            while en.MoveNext() do
                yield en.Current 
        else
            yield d }
like image 105
kaefer Avatar answered Oct 22 '22 16:10

kaefer