Port of Python's difflib.SequenceMatcher class

Bill Baxter dnewsgroup at billbaxter.com
Wed Dec 6 16:30:07 PST 2006


Michael Butscher wrote:

> - One thing I really missed in D was the get() method for Python 
> dictionaries with a default argument. Therefore I created inner 
> functions like
> 
>         IndexType j2lenget(IndexType i, IndexType def)
>         {
>             IndexType* result = i in j2len;
>             if (result)
>                 return *result;
>             else
>                 return def;
>         }
> 
> Probably this can be done more elegantly, but I personally think that
> get() should be a standard method of AAs.

+1.  Me too.

If IFTI were smarter, something like this would do the trick:

V get(V,K)(V[K] dict, K key, V def = V.init)
{
     V* ptr = key in dict;
     return ptr? *ptr: def;
}

The property trick works for AA's too so taking one instance of that:

char[] get(char[][int] dict, int key, char[] def = null)
{
     char[]* ptr = key in dict;
     return ptr? *ptr: def;
}

you can do:

     char[][int] i2s;
     i2s[1] = "Hello";
     i2s[5] = "There";

     writefln( i2s.get(1, "yeh") );
     writefln( i2s.get(2, "default") );
     writefln( i2s.get(1) );
     writefln( i2s.get(2) );

Too bad the template version doesn't work.
D doesn't seem to be able to pick out the V and K from an associative 
array argument.

--bb



More information about the Digitalmars-d-announce mailing list