Dart

Implementation of programming language Dart

Dart is the reference and (so far) the only implementation of Dart language.

Dart platform includes:

  • dart — the standalone virtual machine (VM)
  • dart2js — the Dart to JavaScript compiler
  • dartanalyzer — the static analyzer
  • pub — the Dart package manager
  • dartdoc — the API documentation generator
  • Dart Editor — a tool for editing, debugging, and running Dart applications
  • Dartium — a special version of Chromium that includes the Dart VM

Examples:

Hello, World!:

Example for versions Dart 1.1.1

The “fat arrow” ( => expr; ) syntax is a shorthand for { return expr; }.

main() => print("Hello, World!");

Factorial:

Example for versions Dart 1.1.1

This example uses recursive factorial definition. int datatype is an integer of arbitrary size.

int factorial(int n) => n == 0 ? 1 : n * factorial(n - 1);

main() {
  for (int i = 0; i <= 16; ++i) {
    print('$i! = ${factorial(i)}');
  }
}

Factorial:

Example for versions Dart 1.1.1

This example uses iterative factorial definition.

main() {
  int fact = 1;
  for (int i = 0; i <= 16; ++i, fact *= i) {
    print('$i! = $fact');
  }
}

Fibonacci numbers:

Example for versions Dart 1.1.1

This example uses recursive definition of Fibonacci numbers. Note that the language requires explicit conversion from int to String.

int fibonacci(int n) => n <= 2 ? 1 : fibonacci(n - 2) + fibonacci (n - 1);

main() {
  String output = "";
  for (int i = 1; i <= 16; ++i) {
    output += fibonacci(i).toString() + ", ";
  }
  print(output + "...");
}

Quadratic equation:

Example for versions Dart 1.1.1
import 'dart:io';
import 'dart:math' show sqrt;

int readInt() {
  String input = stdin.readLineSync();
  return int.parse(input);
}

main() {
  int A, B, C;
  try {
    A = readInt();
    B = readInt();
    C = readInt();
  }
  on FormatException {
    print("Coefficient is not a number.");
    return;
  }
  if (A == 0) {
    print("Not a quadratic equation.");
    return;
  }
  int D = B * B - 4 * A * C;
  double p1 = - B / 2.0 / A;
  double p2 = sqrt(D.abs()) / 2.0 / A;
  if (D == 0) {
    print("x = $p1");
  } else {
    if (D > 0) {
      print("x1 = ${p1 + p2}");
      print("x2 = ${p1 - p2}");
    } else {
      print("x1 = ($p1, $p2)");
      print("x2 = ($p1, ${-p2})");
    }
  }
}

CamelCase:

Example for versions Dart 1.1.1

splitMapJoin splits the string into parts that match the pattern and parts that don’t match it, converts each part using corresponding function (in this case capitalizes matches and removes non-matches), and combines the results into a new string.

import 'dart:io';

main() {
  String text = stdin.readLineSync().toLowerCase();
  String capitalize(Match m) => m[0].substring(0, 1).toUpperCase() + m[0].substring(1);
  String skip(String s) => "";
  print(text.splitMapJoin(new RegExp(r'[a-z]+'), onMatch: capitalize, onNonMatch: skip));  
}