Control structures beyond standard conditionals and loops?
Asked Answered
D

4

7

Structured programming languages typically have a few control structures, like while, if, for, do, switch, break, and continue that are used to express high-level structures in source code.

However, there are many other control structures that have been proposed over the years that haven't made their way into modern programming languages. For example, in Knuth's paper "Structured Programming with Go To Statements," page 275, he references a control structure that looks like a stripped-down version of exception handling:

loop until event1 or event2 or ... eventN
   /* ... */
   leave with event1;
   /* ... */
repeat;
then event1 -> /* ... code if event1 occurred ... */
     event2 -> /* ... code if event2 occurred ... */
     /* ... */
     eventN -> /* ... code if eventN occurred ... */
fi;

This seems like a useful structure, but I haven't seen any languages that actually implement it beyond as a special case of standard exception handling.

Similarly, Edsger Dijkstra often used a control structure in which one of many pieces of code is executed nondeterministically based on a set of conditions that may be true. You can see this on page 10 of his paper on smoothsort, among other places. Sample code might look like this:

do
    /* Either of these may be chosen if x == 5 */
    if x <= 5 then y = 5;
    if x >= 5 then y = 137; 
od;

I understand that historically C influenced many modern languages like C++, C#, and Java, and so many control structures we use today are based on the small set offered by C. However, as evidenced by this other SO question, we programmers like to think about alternative control structures that we'd love to have but aren't supported by many programming languages.

My question is this - are there common languages in use today that support control structures radically different from the C-style control structures I mentioned above? Such a control structure doesn't have to be something that can't be represented using the standard C structures - pretty much anything can be encoded that way - but ideally I'd like an example of something that lets you approach certain programming tasks in a fundamentally different way than the C model allows.

And no, "functional programming" isn't really a control structure.

Dollarbird answered 31/7, 2011 at 3:4 Comment(6)
just a small side note: for years I wanted a "for...else" construct and only a few months ago I found out it is possible in Python.Sternberg
@Radagaisus: What's "for...else"?Dempster
@Mehrdad: The else block in a for-else loop executes if the loop terminates naturally (not by breaking). This applies no matter how many iterations (even zero).Cupid
it does what BoltClock said. I always felt too verbose when writing loops with var found = false. More info.Sternberg
@BoltClock: Ah I see... weird, lol.Dempster
@Mehrdad: I know, right?Cupid
A
2
  • Since Haskell is lazy, every function call is essentially a control structure.
  • Pattern-matching in ML-derived languages merges branching, variable binding, and destructuring objects into a single control structure.
  • Common Lisp's conditions are like exceptions that can be restarted.
  • Scheme and other languages support continuations which let you pause and resume or restart a program at any point.
Anethole answered 2/8, 2011 at 1:16 Comment(0)
S
1

(I don't know a lot about the subject so I marked this a wiki)

Haskell's Pattern Matching.

Plain example:

sign x |  x >  0        =   1
       |  x == 0        =   0
       |  x <  0        =  -1

or, say, Fibonacci, which looks almost identical to the math equation:

fib x | x < 2       = 1
      | x >= 2      = fib (x - 1) + fib (x - 2)
Sternberg answered 31/7, 2011 at 3:4 Comment(0)
B
1

Perhaps not "radically different" but "asynchronous" control structures are fairly new.

Async allows non-blocking code to be executed in parallel, with control returning to the main program flow once completed. Although the same could be achieved with nested callbacks, doing anything non-trivial in this way leads to fugly code very quickly.

For example in the upcoming versions of C#/VB, Async allows calling into asynchronous APIs without having to split your code across multiple methods or lambda expressions. I.e. no more callbacks. "await" and "async" keywords enable you to write asynchronous methods that can pause execution without consuming a thread, and then resume later where it left off.

// C#
async Task<int> SumPageSizesAsync(IList<Uri> uris)
{
    int total = 0;
    var statusText = new TextBox();

    foreach (var uri in uris)
    {
        statusText.Text = string.Format("Found {0} bytes ...", total);
        var data = await new WebClient().DownloadDataTaskAsync(uri);
        total += data.Length;
    }

    statusText.Text = string.Format("Found {0} bytes total", total);
    return total;
}

(pinched from http://blogs.msdn.com/b/visualstudio/archive/2011/04/13/async-ctp-refresh.aspx)

For Javascript, there's http://tamejs.org/ that allows you to write code like this:

var res1, res2;
await {
    doOneThing(defer(res1));
    andAnother(defer(res2));
}
thenDoSomethingWith(res1, res2);
Bloomy answered 31/7, 2011 at 3:4 Comment(0)
D
1

C#/Python iterators/generators

def integers():
    i = 0
    while True:
        yield i
        i += 1
Dempster answered 31/7, 2011 at 3:39 Comment(2)
Which is pretty much like lazy evaluation. for example, in Haskell: take 2 [1,2,3,4] -> [1,2].Sternberg
@Radagaisus: No, it's not. It's more like coroutines -- a completely different concept (i.e. pausing/resuming functions in the middle of execution). The fact that it's "delayed" has nothing to do with this.Dempster

© 2022 - 2024 — McMap. All rights reserved.