我已经阅读了一些关于所有主题的文章,但我并没有完全区分.
procedural-programming functional-programming structured-programming
当使用返回块的方法时,它们可以非常方便.但是,当你必须将它们中的一些串在一起时,它会很快变得混乱
例如,您必须连续调用4个URL:
[remoteAPIWithURL:url1 success:^(int status){
[remoteAPIWithURL:url2 success:^(int status){
[remoteAPIWithURL:url3 success:^(int status){
[remoteAPIWithURL:url2 success:^(int status){
//succes!!!
}];
}];
}];
}];
Run Code Online (Sandbox Code Playgroud)
因此,对于每次迭代,我都会更深入一级,我甚至还没有处理嵌套块中的错误.
当存在实际循环时,它会变得更糟.例如,假设我想以100个块的形式上传文件:
- (void) continueUploadWithBlockNr:(int)blockNr
{
if(blocknr>=100)
{
//success!!!
}
[remoteAPIUploadFile:file withBlockNr:blockNr success:^(int status)
{
[self continueUploadWithBlockNr:blockNr];
}];
}
Run Code Online (Sandbox Code Playgroud)
这感觉非常不直观,并且非常快速地变得非常难以理解.
在.Net中,他们使用async和await关键字解决了所有这些问题,基本上将这些延续展开为一个看似同步的流程.
Objective C中的最佳实践是什么?
lambda continuations objective-c structured-programming objective-c-blocks
唐纳德克努特的计算机编程艺术系列使用他自己的程序汇编语言MIX.现在,问题变成了:Knuth是否应该使用函数式语言来描述他的算法?TeX是否应该用函数式语言编写?
计算机具有程序架构.计算的根源是否意味着最好的分支?
最初的AoCP是用MIX编写的.更新后的AoCP使用了基于更现代架构的MMIX.
但是,基本点仍然存在.Knuth从一个程序架构转到另一个......显然不需要函数式编程.
procedural-programming functional-programming knuth structured-programming
结构化编程语言通常有几个控制结构,比如while,if,for,do,switch,break,并且continue被用来表示在源代码中的高层次结构.
然而,多年来提出的许多其他控制结构尚未进入现代编程语言.例如,在Knuth的论文" 使用转到语句进行结构化编程 "(第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;
Run Code Online (Sandbox Code Playgroud)
这似乎是一个有用的结构,但我还没有看到任何实际实现它的语言作为标准异常处理的特殊情况.
类似地,Edsger Dijkstra经常使用一种控制结构,其中许多代码之一基于可能为真的一组条件而不确定地执行.你可以在他关于smoothsort等论文的第10页上看到这一点.示例代码可能如下所示:
do
/* …Run Code Online (Sandbox Code Playgroud) programming-languages control-structure structured-programming
情况:你有一个嵌套循环,你需要突破它.
让我们来看看这个经典的例子(经典,因为它来自Goto Consideredred Harmful Considered Harmful):给定一个二维NxN方形整数矩阵X,找到没有零的第一行.
我将通过几种不同语言解决这个问题的方法.我想我应该如何开始能写,但并非如此.
//using "chained breaks"
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if( X[i][j] == 0 ){
//this row isn't non-zero, so go to the next row
break continue;
//break out of the inner loop and continue the outer loop
}
}
//if we get to here, we know this row doesn't have zeroes
return i;
}
return -1; //failure; exact val doesn't matter for this question
Run Code Online (Sandbox Code Playgroud)
C及其主要忠实的衍生品:
//goto
for(int …Run Code Online (Sandbox Code Playgroud)