digitalmars.D.learn - Equivalent of FirstOrDefault with ranges
- Lutger (18/18) Sep 01 2016 I was looking for something like FirstOrDefault* from .NET in
- Cauterite (4/4) Sep 02 2016 On Friday, 2 September 2016 at 06:56:07 UTC, Lutger wrote:
- Nicholas Wilson (8/26) Sep 02 2016 ElementType!R firstOrDefault(R)(R r, ElementType!R def =
I was looking for something like FirstOrDefault* from .NET in 
phobos. For example, I have this piece of code:
string findBobOrReturnNull(string[] names)
{
     auto r = names.find("bob");
     if(r.empty) return null;
     return r.front;
}
assert(findBobOrReturnNull(["alice", "bob"]) == "bob");
assert(findBobOrReturnNull(["alice"]) is null);
How can I turn that into something like this, or is there another 
idiomatic way to write it as a single expression?
string findBobOrReturnNull(string[] names)
{
     return names.find("bob").firstOrDefault;
}
* 
https://msdn.microsoft.com/en-us/library/bb340482%28v=vs.110%29.aspx
 Sep 01 2016
On Friday, 2 September 2016 at 06:56:07 UTC, Lutger wrote:You could do: names.find("bob").chain(only(``)).front; It's not very expressive though.
 Sep 02 2016
On Friday, 2 September 2016 at 06:56:07 UTC, Lutger wrote:
 I was looking for something like FirstOrDefault* from .NET in 
 phobos. For example, I have this piece of code:
 string findBobOrReturnNull(string[] names)
 {
     auto r = names.find("bob");
     if(r.empty) return null;
     return r.front;
 }
 assert(findBobOrReturnNull(["alice", "bob"]) == "bob");
 assert(findBobOrReturnNull(["alice"]) is null);
 How can I turn that into something like this, or is there 
 another idiomatic way to write it as a single expression?
 string findBobOrReturnNull(string[] names)
 {
     return names.find("bob").firstOrDefault;
 }
 * 
 https://msdn.microsoft.com/en-us/library/bb340482%28v=vs.110%29.aspx
ElementType!R firstOrDefault(R)(R r, ElementType!R def = 
(ElementType!R).init)
        if(isInputRange!R)
{
     if(r.empty) return def;
     return r.front;
}
 Sep 02 2016








 
  
  
 
 Cauterite <cauterite gmail.com>
 Cauterite <cauterite gmail.com> 