标准条件和循环之外的控制结构?

发布于 2024-11-27 07:11:35 字数 1551 浏览 3 评论 0原文

结构化编程语言通常有一些控制结构,例如 whileiffordoswitchbreakcontinue 用于在源代码中表达高级结构。

然而,多年来提出的许多其他控制结构尚未进入现代编程语言。例如,在 Knuth 的论文“使用 Go To 语句进行结构化编程,”第 275 页,他引用了一个看起来像异常的精简版本的控制结构处理:

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;

这似乎是一个有用的结构,但我还没有看到任何语言实际将其实现为标准异常处理的特殊情况。

类似地,Edsger Dijkstra 经常使用一种控制结构,在该结构中,根据一组可能为真的条件,不确定地执行多段代码中的一段。您可以在他关于 smoothsort 的论文第 10 页上看到此内容等地方。示例代码可能如下所示:

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

我知道 C 历史上影响了许多现代语言,例如 C++、C# 和 Java,并且我们今天使用的许多控制结构都基于 C 提供的小型集合。但是, 正如另一个SO问题所证明的,我们程序员喜欢考虑我们想要但没有的替代控制结构不支持许多编程语言。

我的问题是 - 当今使用的通用语言是否支持与我上面提到的 C 风格控制结构完全不同的控制结构?这样的控制结构不一定是可以的。不能使用标准 C 结构来表示 - 几乎任何东西都可以用这种方式编码 - 但理想情况下,我想要一个示例,它可以让您以与 C 模型允许的根本不同的方式处理某些编程任务。

不,“函数式编程”并不是真正的控制结构。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゃ人海孤独症 2024-12-04 07:11:35
  • 由于 Haskell 是惰性每个函数调用本质上是一个控制结构。
  • ML 派生语言中的模式匹配将分支、变量绑定和解构对象合并到一个单一控制结构。
  • Common Lisp 的 条件 就像可以重新启动。
  • Scheme 和其他语言支持延续,让您可以随时暂停、恢复或重新启动程序。
  • 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.
风透绣罗衣 2024-12-04 07:11:35

也许不是“完全不同”,但“异步”控制结构是相当新的。

异步允许并行执行非阻塞代码,一旦完成,控制权就会返回到主程序流。尽管通过嵌套回调也可以实现同样的效果,但以这种方式做任何不平凡的事情很快就会导致代码变得混乱。

例如,在即将推出的 C#/VB 版本中,Async 允许调用异步 API,而无需将代码拆分为多个方法或 lambda 表达式。即不再有回调。 “await”和“async”关键字使您能够编写异步方法,这些方法可以在不消耗线程的情况下暂停执行,然后在稍后从中断处恢复。

// 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;
}

(摘自 http://blogs。 msdn.com/b/visualstudio/archive/2011/04/13/async-ctp-refresh.aspx

对于 Javascript,有 http://tamejs.org/ 允许您编写如下代码:

var res1, res2;
await {
    doOneThing(defer(res1));
    andAnother(defer(res2));
}
thenDoSomethingWith(res1, res2);

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);
夏日落 2024-12-04 07:11:35

C#/Python 迭代器/生成器

def integers():
    i = 0
    while True:
        yield i
        i += 1

C#/Python iterators/generators

def integers():
    i = 0
    while True:
        yield i
        i += 1
笛声青案梦长安 2024-12-04 07:11:35

(我对这个主题了解不多,所以我将其标记为 wiki)

Haskell 模式匹配

简单的例子:

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

或者说斐波那契,它看起来几乎与数学方程相同:

fib x | x < 2       = 1
      | x >= 2      = fib (x - 1) + fib (x - 2)

(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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文