Thread overview
Associative arrays and foreach.
Sep 13, 2003
Walter
September 12, 2003
Didn't try the new foreach statement until today. Works great with normal arrays but I don't know how to iterate over an associative array and obtain "key" and "value" pairs for each item.

I think it should be something along the lines of:

void main()
{
    char[][char[]] hash;
    hash["en"] = "Hello, world!";
    hash["es"] = "¡Hola, mundo!";

    foreach (char[] key: char[] value; hash)
    {
        printf("- %.*s\n", value);
    }
}

But the compiler doesn't support it. The thing is that "Hashtable" objects will be forced to provide two overloaded "apply" functions:


template MyArray(T)
{
    struct Hashtable
    {
        operator apply(int delegate(T value) dg);
        operator apply(int delegate(char[] key, T value) dg);
    }
}

Wich probably will collide with what was discussed in the "Multiple parameter foreach" thread.


September 12, 2003
"Julio César Carrascal Urquijo" <adnoctum@phreaker.net> wrote in message
news:bjtja5$1q5n$1@digitaldaemon.com...
| Didn't try the new foreach statement until today. Works great with normal
| arrays but I don't know how to iterate over an associative array and
obtain
| "key" and "value" pairs for each item.
|
| I think it should be something along the lines of:
|
| void main()
| {
|     char[][char[]] hash;
|     hash["en"] = "Hello, world!";
|     hash["es"] = "¡Hola, mundo!";
|
|     foreach (char[] key: char[] value; hash)
|     {
|         printf("- %.*s\n", value);
|     }
| }
|

This is what I've done:

foreach ( char [] key; hash.keys )
    printf("%.*s\n",hash[key]);

It isn't pretty, but it works.

————————————————————————— Carlos Santander


---

Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.516 / Virus Database: 313 - Release Date: 2003-09-01


September 13, 2003
"Julio César Carrascal Urquijo" <adnoctum@phreaker.net> wrote in message news:bjtja5$1q5n$1@digitaldaemon.com...
> Didn't try the new foreach statement until today. Works great with normal arrays but I don't know how to iterate over an associative array and
obtain
> "key" and "value" pairs for each item.
>
> I think it should be something along the lines of:
>
> void main()
> {
>     char[][char[]] hash;
>     hash["en"] = "Hello, world!";
>     hash["es"] = "¡Hola, mundo!";
>
>     foreach (char[] key: char[] value; hash)
>     {
>         printf("- %.*s\n", value);
>     }
> }

I think I'll be adding that to foreach. But I am glad that foreach is turning out to be pretty popular!


September 13, 2003
>
> I think I'll be adding that to foreach. But I am glad that foreach is turning out to be pretty popular!
>

Yes, specially for those of us with a scripting background.

I work every day with PHP and Python (the "for" in Python is really a "foreach") and this construct is basic for "everything" that you need to do.