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

thedeemon via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 14 04:32:53 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)

This reminds me of a function in OCaml extended stdlib that I've 
used quite often and really miss in D:

filter_map : ('a -> 'b option) -> 'a list -> 'b list

"filter_map f l call (f a0) (f a1).... (f an) where a0..an are 
the elements of l. It returns the list of elements bi such as f 
ai = Some bi (when f returns None, the corresponding element of l 
is discarded)."

Or its variant for OCaml's analog of ranges:

filter_map : ('a -> 'b option) -> 'a t -> 'b t

"filter_map f e returns an enumeration over all elements x such 
as f y returns Some x, where y is an element of e."

It is really convenient and comes handy in many situations. 
However it requires some common Option/Maybe type that different 
libraries could use.



More information about the Digitalmars-d mailing list