[Request] A way to extract all instance of X from a range

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 14 02:42:40 PDT 2016


On Monday, 14 March 2016 at 08:04:18 UTC, deadalnix wrote:
> Right now, I'm repeating the following pattern many times :
>
> range.map!(x => cast(Foo) x).filter!(x => x !is null)
>
> Which is kind of annoying. Could we get something in phobos to 
> do this ?

BTW, .NET has an extension method called OfType<T> that does the 
same thing:
https://msdn.microsoft.com/library/bb360913(v=vs.100).aspx
which is different from Cast<T>, which throws an exception if an 
element can't be converted:
https://msdn.microsoft.com/library/bb341406(v=vs.100).aspx

How do you want to handle this? With two separate methods as in 
.NET, or with a template parameter?

Maybe something like this:

/// Returns a range that lazily iterates over
/// the elements in `source` and converts each
/// of them to type `T`.
///
/// If `throwOnConvError` is false, elements
/// that can't be converted will be skipped.
auto ofType
     (T, bool throwOnConvError = true, Range)
     (Range source)
     if (isInputRange!Range)



More information about the Digitalmars-d mailing list