Menu

Enumerable "Choose" function

Help
2014-11-10
2014-11-10
  • Mauricio Scheffer

    Hi, I'm missing a function like F#'s Seq.choose or Haskell's catMaybes in Sasa, e.g.:

    public static IEnumerable<T> Choose<T>(this IEnumerable<Option<T>> source)
    {
        return source.SelectMany(x =>
        {
            T v;
            return x.TryGetValue(out v) ? new[] {v} : Enumerable.Empty<T>();
        });
    }
    

    Is this missing intentionally for some reason? Otherwise, do you think it's worth adding it to the library?

    Cheers,
    Mauricio

     
  • naasking

    naasking - 2014-11-10

    Not intentional, choose/catMaybe just wasn't part of the standard Linq interface. It almost seems too short to include unless it really comes up everywhere:

    source.Where(x => x != null).Select(x => x.Value);
    

    Or:

    source.Where(x => x.HasValue).Select(x => x.Value);
    

    Does it come up often enough in your programs to warrant special-casing? If so, I don't like the catMaybe name, so what's the rationale behind "choose", as opposed to some variant of "filter" or "except"? I know Seq.filter is used in F#, but unless it causes the compiler to fail, I don't think I should be beholden to that convention in Sasa.

     
  • Mauricio Scheffer

    It really pops up everywhere in my programs, and I dislike the Value property enough to be thinking about writing an FxCop rule or something similar to disallow it :)

    I can't come up with a good name for this, everything seems vague in one way or another.
    I'd rule out "except" as it could be confused with Enumerable.Except ( http://msdn.microsoft.com/en-us/library/vstudio/bb300779.aspx ).
    FWIW ocaml-core calls this filter_opt ( https://ocaml.janestreet.com/ocaml-core/111.28.00/doc/core_kernel/#Sequence ).

    Anyway it's no big deal, I can keep this as an extension method in my code, just wondering if it was useful to be included in the library.

    Cheers,
    Mauricio

     

    Last edit: Mauricio Scheffer 2014-11-10
  • Mauricio Scheffer

    Some more name ideas: WhereNotNone, WhereSome, FilterNone

     
  • naasking

    naasking - 2014-11-10

    You dislike the value property because it throws an exception when HasValue is false?

    I was thinking FilterNull or ExceptNull. I was going to provide an overload for IEnumerable<t?> as well.</t?>

     
  • Mauricio Scheffer

    Indeed, IMHO Value is an unnecessarily partial function and a case of "boolean blindness".
    Good idea to apply this to IEnumerable<t?> as well, I like the name.</t?>

    Cheers,
    Mauricio

     
  • naasking

    naasking - 2014-11-10

    It's absolutely boolean blindness, but other than the matching function you brought up in the other thread, I don't have a better alternative for C# that can be used in all contexts, like Linq expressions.

     

Log in to post a comment.

MongoDB Logo MongoDB