www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Associative array .get with .init as default second argument

reply Torarin <torarind gmail.com> writes:
The AA .get function is defined like this:

    Value get(Key key, lazy Value defaultValue)
    {
        auto p = key in *cast(Value[Key]*)(&p);
        return p ? *p : defaultValue;
    }

Can we also have an overload that uses Value's init value as fallback?
That would simplify checks like this:

    if (headers.get("transfer-encoding", "") == "chunked")
    if (headers.get("transfer-encoding") == "chunked")

This is what STL map's operator [] does, and I think it's handy. It
only requires the addition of this overload:

    Value get(Key key)
    {
        auto p = key in *cast(Value[Key]*)(&p);
        return p ? *p : Value.init;
    }

It would also make these kind of accesses more efficient, since you
skip the lazy delegate.
Oct 18 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
Torarin:

 This is what STL map's operator [] does, and I think it's handy. It
 only requires the addition of this overload:
 
     Value get(Key key)
     {
         auto p = key in *cast(Value[Key]*)(&p);
         return p ? *p : Value.init;
     }
In what cases is this useful? Are you able to show me an example of situation where it is useful? Bye, bearophile
Oct 18 2010
next sibling parent Torarin <torarind gmail.com> writes:
The useful situation is when you care only about the presence of a
certain value in a given key. I actually gave an example of it.
Oct 18 2010
prev sibling parent Torarin <torarind gmail.com> writes:
2010/10/18 bearophile <bearophileHUGS lycos.com>:
 In what cases is this useful? Are you able to show me an example of situation
where it is useful?

 Bye,
 bearophile
Bearophile, I probably didn't make it very clear, so I'll try again: Now: if (headers.get("transfer-encoding", "") == "chunked") More appealing in my opinion: if (headers.get("transfer-encoding") == "chunked") In other words: "Does this key-value pair exist?" Another example from the HTTP domain: if(headers.get("connection", "") == "close")
Oct 21 2010