www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18759] New: feature request: blocks

https://issues.dlang.org/show_bug.cgi?id=18759

          Issue ID: 18759
           Summary: feature request: blocks
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: default_357-line yahoo.de

Blocks are a generalization of foreach opApply overloading. They allow
any struct expression to be followed by a statement, which is packaged
into a delegate that returns a control flow type (or, if you want to be
cheap about it, an int like opApply does) and passed to opBlock in
the struct, which decides the control flow of the statement.

Advantages:
 * callback-heavy code looks a lot more straightforward
 * break/continue/return can be used from within what would otherwise be
callbacks
 * reduce lambda abuse for control flow (.each is a natural candidate)
 * comparatively little effort because it's just an extension of opApply

Example:

import core.controlflow;

struct indefinitely
{
  // alternatively: opBlockLoop for 'opBlock that handles break/continue'
  static ControlFlow opBlock(ControlFlow delegate() action)
  {
    while (true)
    {
      auto flow = action();
      // flow.ended: control flow reached end of block
      // otherwise, something like a return statement, break, continue or goto
      if (!flow.ended) return flow;
    }
}

Usage:

indefinitely {
  writeln("This is repeated indefinitely.");
}

Other cool example:

If combined with variable declaration expressions, a construct like foreach can
in theory be implemented entirely in the library:

ForeachStruct foreach(T)(T iterable, out int indexVariable, out ElementType!T
loopVariable) - array.foreach(int index, auto value) { return value; }

--
Apr 13 2018