MKoD - D Programming Language

Associative Array example using a char[] as the key in D - code-name assocarray.d

Basic Newbie Stuff Associative Array example using a char[] as the key example:

// assocarray.d - last tested with D v1.0
// To Compile: C:\dmd\MKoD_ex>dmd assocarray.d
private import std.stdio;

alias char[] string;

void main()
{
     string[ string ] arr;
 
     // before adding "key"
     writefln( "With the associative array empty, does \"key\" exist? %s", 
               ( isset( arr, "key" ) ? "yes" : "no" ) );
     writefln();

     writefln( "Now adding entries \"key\" and \"key2\"" );
     arr[ "key"  ] = "added a key";
     arr[ "key2" ] = "added another key";
     writefln();

     writefln( "The associative array now has %d entries listed below.", 
                arr.length );
     displayEntries( arr );
     writefln();

     // after adding "keys"
     writefln( "After adding the keys, does \"key\" exist? %s", 
               ( isset( arr, "key" ) ? "yes" : "no" ) );
     writefln();

     writefln( "Now removing \"key2\"..." );
     remove( arr, "key2" );
     // after removing "key2"
     writefln( "After removing, does \"key2\" now exist? %s", 
               ( isset( arr, "key2" ) ? "yes" : "no" ) );
     writefln( "The associative array now has %d entries.", arr.length );
     writefln();

     writefln( "Before ending display all remaining keys..." );
     displayEntries( arr );

} // end void main()

bool isset( in string[ string ] arr, in char[] sKey )
{
    if ( ( sKey in arr ) != null )
        return true;
    else 
        return false;
}

void remove( inout string[ string ] arr, in char[] sKey )
{
    arr.remove( sKey );
} 

void removeall( inout string[ string ] arr )
{
    foreach( char[] sKey; arr.keys )
        arr.remove( sKey );
}

void displayEntries( in string[ string ] arr )
{
    foreach( char[] sKey, char[] sValue; arr )
        writefln( "sKey=\"%s\", sValue=\"%s\"", sKey, sValue );
}
C:\dmd\MKOD_ex>dmd assocarray.d
C:\dmd\bin\..\..\dm\bin\link.exe assocarray,,,user32+kernel32/noi;

C:\dmd\MKOD_ex>assocarray
With the associative array empty, does "key" exist? no

Now adding entries "key" and "key2"

The associative array now has 2 entries listed below.
sKey="key", sValue="added a key"
sKey="key2", sValue="added another key"

After adding the keys, does "key" exist? yes

Now removing "key2"...
After removing, does "key2" now exist? no
The associative array now has 1 entries.

Before ending display all remaining keys...
sKey="key", sValue="added a key"

C:\dmd\MKOD_ex>
Mars: fourth Rock from the Sun.