Is there an equivalent to F # Enumerable.DefaultIfEmpty?

After searching a bit, I could not find the equivalent of F # Enumerable.DefaultIfEmpty .

Is there something similar in F # (possibly in a different, idiomatic sense)?

+4
source share
3 answers

Seqwork and return functions IEnumerable<_>and DefaultIfEmptyand return IEnumerable<_>. How about just wrap it in a function that is composite.

let inline DefaultIfEmpty d l = System.Linq.Enumerable.DefaultIfEmpty(l, d)

It also saves laziness.

Example:

Seq.empty |> DefaultIfEmpty 0

Update

I created an open source library in which many extension methods and statics were added, including Enumerable.defaultIfEmpty- ComposableExtesions

+3
source

, .

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 }
+6

:

  • DefaultIfEmpty, ,
  • :

    let DefaultIfEmpty (l:'t seq) (d:'t) = 
        match Seq.length l with |0 -> seq [d] |_ -> l
    
  • let DefaultIfEmpty (l:'t seq) (d:'t) = 
        match Seq.isEmpty l with |true -> seq [d] |false -> l
    
+4
source

Source: https://habr.com/ru/post/1525180/


All Articles