Fetching an element using find

lithium iodate whatdoiknow at doesntexist.net
Mon Jan 13 18:28:52 UTC 2020


On Monday, 13 January 2020 at 17:58:57 UTC, Steven Schveighoffer 
wrote:
> On 1/13/20 12:47 PM, H. S. Teoh wrote:
>> 
>> Why not write your own convenience wrapper?
>> 
>> 	auto firstElement(R)(R r)
>> 		if (isInputRange!R)
>> 	{
>> 		if (r.empty) throw new Exception(...);
>> 		return r.front;
>> 	}
>> 
>> 	auto e = myData.find!(e => blah(e)).firstElement;
>
> I certainly can (and did). I was wondering if there was 
> something in Phobos to do it.
>
> -Steve

`adjoin` can be used to run an inline lambda:
auto answer = arr.find!((item,x) => item.id == 
x)(id).adjoin!((n){enforce(!n.empty); return n.front;});

Using a simple alias you can have a flexible and nice to read 
solution:
alias ensure(alias pred) = (n, const(char)[] msg = "`ensure` 
failed"){enforce(pred(n), msg); return n;}; // module scope for 
UFCS!

auto answer = arr.find!((item,x) => item.id == x)(id).ensure!(n 
=> !n.empty).front;
or with custom message:
auto answer = arr.find!((item,x) => item.id == x)(id).ensure!(n 
=> !n.empty)("element with id not found").front;


More information about the Digitalmars-d-learn mailing list