Dart - gregorymorrison/euler1 GitHub Wiki

I took an initial look at one of Google's newest technologies today, Dart. Introduced in 2009, it's supposed to be a modernized replacement for JavaScript, adding features such as OOP, optional static types, and shared libraries, and addressing issues such as performance optimization and better security. The Dart compiler compiles your code into JS for execution in the browser. Since any given Dart code has an equivalent JS translation, I'm not sure how the Dart team sees that they can overcome JS's deficiencies. Also, I think that JS is so entrenched, that even a company the size of Google will have a hard time dethroning JS. Still, being no fan of JS, I wish them well...

To my eyes, it looks pretty much like JavaScript. In fact, it literally took me less than five minutes from the time I first looked at Dart to write this version of Euler1:

// Euler1 in Dart

int euler1(int size) {
   var retval = 0;

   for(int i=1; i<size; i++)
     if (i%3==0 || i%5==0)
            retval += i;

   return retval ;
}

main() {
    print(euler1(1000));
}

After writing a functional version of Euler1 in JavaScript, I decided to try my hand at it with Dart. Although for any Imperative code there should be an equivalent Functional translation, I was not completely success. This language still feels a little immature. My attempt is not terrible to read, though.

// Euler1 in Dart

List<int> _range(int lo, int hi, List<int> acc) {
    if (lo == hi) {
        return acc;
    } else {
        acc.add(lo);
        return _range(lo+1, hi, acc);
    }
}

List<int> range(int lo, int hi) {
    return _range(lo, hi, new List<int>());
}

main() {
    List<int> ints = range(0, 1000);

    List<int> mapped = new List<int>();
    ints.forEach((i) => mapped.add(i));

    List<int> filtered = mapped.filter((i) => i%3==0 || i%5==0);

    int reduced = 0;
    filtered.forEach((i) => reduced += i);

    print (reduced);
}

Dart has no range generator, so I rolled my own. And Filter is already built into the language, though Map and Reduce are not. I couldn't figure out how to avoid the mutables state of acc, mapped, and reduced. Let me know if you can figure it out.

Dart's home page opens up to an interactive code editor, complete with samples, which lets you immediately play with the language. Nothing to install - brilliant! To run, just put your code in the online editor and click the big Run button:

233168
⚠️ **GitHub.com Fallback** ⚠️