D: Delegates look like closures

January 22nd, 2008 Leave a comment Go to comments

This is an example that shows that closures in D can look like closures. The program asks the user for a password (which is “secret”). If the user enters the wrong password he has two more tries before the program terminates.

import std.stdio;

bool retry(int times, bool delegate() dg)
{
  int tries = 0;
  while (tries++ < times) {
    if(dg())
      return true;
  }
  return false;
}

void main() {
  retry(3, {
    writefln("Password please: ");
    char[] buf = readln();
    return (buf == "secretn");
  });
}