In this example, I try to use D Voldemore (fantastic) functionallity to implement a pattern usually used in javascript.

Basically, a function closure represents the state, and the methods to access this state are returned in the form of union (union has not state itself).

void main(){
  assert(number(10).next.value==11 );
  assert(zero()==number(0) );
  assert(zero()==number(1).previous );
  auto ten = number(10);
  auto nine = ten.previous;
  assert(nine == number(9));
}

auto number(int _value=0){
  struct Number {
    int value() {
      return _value;
    };
    Number next() {
      return number(_value+1);
    };
    Number previous(){
      return number(_value-1);
    };
    int opCmp(Number other){
      return _value - other.value;
    };
  }

  return Number();
}

auto zero() {
  return number(0);
}

Problem is that Union methods needs to call it's containing function and compiler doesn't accept it:

main.d(16): Error: forward reference to inferred return type of function call number(_value + 1) main.d(19): Error: forward reference to inferred return type of function call number(_value - 1)

I know there is another ways to solve this problem easily (without closures), but I was really curious about if it was possible.


Reply via email to