This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,2 @@
{{Control Structures}}
In this task, we document common flow-control structures. One common example of a flow-control structure is the <tt>goto</tt> construct. Note that [[Conditional Structures]] and [[Iteration|Loop Structures]] have their own articles/categories.

View file

@ -0,0 +1,2 @@
---
note: Control Structures

View file

@ -0,0 +1,2 @@
JMP $8000 ;immediately JuMP to $8000 and begin executing
;instructions there.

View file

@ -0,0 +1,2 @@
JMP ($8000) ;immediately JuMP to the address in memory locations
;$8000 and $8001

View file

@ -0,0 +1 @@
JSR $8000 ;Jump to SubRoutine

View file

@ -0,0 +1 @@
RTS ;ReTurn from Subroutine

View file

@ -0,0 +1 @@
BRK ;BReaK

View file

@ -0,0 +1 @@
RTI ;ReTurn from Interrupt

View file

@ -0,0 +1,12 @@
(
FOR j TO 1000 DO
FOR i TO j-1 DO
IF random > 0.999 THEN
printf(($"Exited when: i="g(0)", j="g(0)l$,i,j));
done
FI
# etc. #
OD
OD;
done: EMPTY
);

View file

@ -0,0 +1,12 @@
STRING medal = (
[]PROC VOID award = (gold,silver,bronze);
award[ 1 + ENTIER (random*3)];
gold: "Gold" EXIT
silver: "Silver" EXIT
bronze: "Bronze"
);
print(("Medal awarded: ",medal, new line));

View file

@ -0,0 +1,21 @@
STRING final state = (
INT condition;
PROC do something = VOID: condition := 1 + ENTIER (3 * random);
state1:
do something;
CASE condition IN
state 1, state 2
OUT
state n
ESAC
EXIT
state 2:
"State Two"
EXIT
state n:
"State N"
);
print(("Final state: ",final state, new line));

View file

@ -0,0 +1,22 @@
# example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
determine first generation;
WHILE can represent next generation
DO calculate next generation;
print next generation
OD.
determine first generation:
INT previous := 1, current := 3.
can represent next generation:
current <= max int - previous.
calculate next generation:
INT new = current + previous;
previous := current;
current := new.
print next generation:
printf (($lz","3z","3z","2z-d$, current,
$xz","3z","3z","2z-d$, previous,
$xd.n(real width - 1)d$, current / previous)).

View file

@ -0,0 +1,5 @@
$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8

View file

@ -0,0 +1,3 @@
<<Top>>
Put_Line("Hello, World");
goto Top;

View file

@ -0,0 +1,8 @@
Outer:
loop
-- do something
loop
-- do something else
exit Outer; -- exits both the inner and outer loops
end loop;
end loop;

View file

@ -0,0 +1,7 @@
select
delay 10.0;
Put_Line ("Cannot finish this in 10s");
then abort
-- do some lengthy calculation
...
end select;

View file

@ -0,0 +1,14 @@
MsgBox, calling Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
Goto Label2
MsgBox, calling Label2 ; this part is never reached
Return
Label1:
MsgBox, Label1
Return
Label2:
MsgBox, Label2 will not return to calling routine
Return

View file

@ -0,0 +1,11 @@
GOSUB subroutine
(loop)
PRINT "Infinite loop"
GOTO loop
END
(subroutine)
PRINT "In subroutine"
WAIT 100
RETURN

View file

@ -0,0 +1,8 @@
#include <iostream>
int main()
{
LOOP:
std::cout << "Hello, World!\n";
goto LOOP;
}

View file

@ -0,0 +1,71 @@
#include <iostream>
#include <ostream>
void foo()
{
std::cout << "Going to throw an exception.\n";
throw 7; // almost any object can be thrown, including ints
std::throw << "This output will never execute.\n";
}
void bar()
{
std::cout << "Going to call foo().\n";
foo();
std::cout << "This will be skipped by the exception coming from foo.\n";
}
void baz()
{
try // everything thrown from inside the following code block
{ // will be covered by the following catch clauses
std::cout << "Going to call bar().\n";
bar();
std::cout << "This will be skipped by the exception coming from foo.\n";
}
catch(...) // a simple catch-all, but doesn't give access to the thrown exception
{
std::cout << "An exception occured. I'll just throw it on.\n";
throw; // without an argument, the caught exception is re-thrown
}
std::cout << "This will not be executed due to the re-throw in the catch block\n";
}
void foobar()
{
try
{
baz();
}
catch(char const* s)
{
std::cout << "If foo had thrown a char const*, this code would be executed.\n";
std::cout << "In that case, the thrown char const* would read " << s << ".\n";
}
catch(int i)
{
std::cout << "Caught an int, with value " << i << " (should be 7).\n";
std::cout << "Not rethrowing the int.\n";
}
catch(...)
{
std::cout << "This catch-all doesn't get invoked because the catch(int) above\n"
<< "already took care of the exception (even if it had rethrown the\n"
<< "exception, this catch-all would not be invoked, because it's\n"
<< "only invoked for exceptions coming from the try block.\n";
}
std::cout << "This will be executed, since the exception was handled above, and not rethrown.\n";
}
int main()
{
try
{
foobar();
}
catch(...)
{
std::cout << "The main function never sees the exception, because it's completely handled\n"
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
}
}

View file

@ -0,0 +1,13 @@
int main()
{
int i,j;
for (j=1; j<1000; j++) {
for (i=0; i<j, i++) {
if (exit_early())
goto out;
/* etc. */
}
}
out:
return 0;
}

View file

@ -0,0 +1,7 @@
import std.stdio;
void main() {
label1:
writeln("I'm in your infinite loop.");
goto label1;
}

View file

@ -0,0 +1,22 @@
import std.stdio;
class DerivedException : Exception {
this(string msg) { super(msg); }
}
void main(string[] args) {
try {
if (args[1] == "throw")
throw new Exception("message");
} catch (DerivedException ex) {
// We never threw a DerivedException, so this
// block is never called.
writefln("caught derived exception %s", ex);
} catch (Exception ex) {
writefln("caught exception: %s", ex);
} catch (Throwable ex) {
writefln("caught throwable: %s", ex);
} finally {
writeln("finished (exception or none).");
}
}

View file

@ -0,0 +1,13 @@
import std.stdio;
void main(string[] args) {
scope(exit)
writeln("Gone");
if (args[1] == "throw")
throw new Exception("message");
scope(exit)
writeln("Gone, but we passed the first" ~
" chance to throw an exception.");
}

View file

@ -0,0 +1,13 @@
: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
2DUP @ 0 SWAP WITHIN IF
SWAP 1+ CELLS +
ELSE
1 THROW
THEN ;
8 checked-array myarray
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;

View file

@ -0,0 +1,7 @@
10 LET a=1
20 IF a=2 THEN PRINT "This is a conditional statement"
30 IF a=1 THEN GOTO 50: REM a conditional jump
40 PRINT "This statement will be skipped"
50 PRINT ("Hello" AND (1=2)): REM This does not print
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump

View file

@ -0,0 +1,4 @@
func main() {
inf:
goto inf
}

View file

@ -0,0 +1,18 @@
import "os"
func processFile() {
f, err := os.Open("file")
if err != nil {
// (probably do something with the error)
return // no need to close file, it didn't open
}
defer f.Close() // file is open. no matter what, close it on return
var lucky bool
// some processing
if (lucky) {
// f.Close() will get called here
return
}
// more processing
// f.Close() will get called here too
}

View file

@ -0,0 +1,16 @@
package main
import "fmt"
func printOnes() {
for {
fmt.Println("1")
}
}
func main() {
go printOnes()
for {
fmt.Println("0")
}
}

View file

@ -0,0 +1,8 @@
func answer(phone1, phone2 chan int) {
select {
case <-phone1:
// talk on phone one
case <-phone2:
// talk on phone two
}
}

View file

@ -0,0 +1,12 @@
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Exit
main = do
runExitTMaybe $ do
forM_ [1..5] $ \x -> do
forM_ [1..5] $ \y -> do
lift $ print (x, y)
when (x == 3 && y == 2) $
exitWith ()
putStrLn "Done."

View file

@ -0,0 +1,17 @@
1 GOTO 2 ! branch to label
2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3
3 ALARM(delay, n) ! n=2...9 simulate F2 to F9 keys: call asynchronously "Alarm"-SUBROUTINES F2...F9 with a delay
4 ALARM( 1 ) ! lets HicEst wait at this statement for any keyboard or mouse event
5 SYSTEM(WAIT=1000) ! msec
6 XEQ('CALL my_subroutine', *7) ! executes command string, on error branch to label 7
7 y = EXP(1E100, *8) ! on error branch to label 8
8 y = LOG( 0 , *9) ! on error branch to label 9
9 ALARM( 999 ) ! quit HicEst immediately

View file

@ -0,0 +1,3 @@
test:
..some code here
goto, test

View file

@ -0,0 +1 @@
on_error, test

View file

@ -0,0 +1 @@
on_ioerror, test

View file

@ -0,0 +1 @@
break

View file

@ -0,0 +1 @@
continue

View file

@ -0,0 +1,9 @@
if x := every i := 1 to *container do { # * is the 'length' operator
if container[i] ~== y then
write("item ", i, " is not interesting")
else
break a
} then
write("found item ", x)
else
write("did not find an item")

View file

@ -0,0 +1 @@
break break next

View file

@ -0,0 +1 @@
x := ftn()

View file

@ -0,0 +1,8 @@
&error := 1
mayErrorOut()
if &error == 1 then
&error := 0 # clear the trap
else {
# deal with the fault
handleError(&errornumber, &errortext, &errorvalue) # keyword values containing facts about the failure
}

View file

@ -0,0 +1 @@
runerr(errnumber, errorvalue) # choose an error number and supply the offending value

View file

@ -0,0 +1,2 @@
2 * 1 2 3
2 4 6

View file

@ -0,0 +1,33 @@
switch (xx) {
case 1:
case 2:
/* 1 & 2 both come here... */
...
break;
case 4:
/* 4 comes here... */
...
break;
case 5:
/* 5 comes here... */
...
break;
default:
/* everything else */
break;
}
for (int i = 0; i < 10; ++i) {
...
if (some_condition) { break; }
...
}
_Time_: do {
for (int i = 0; i < 10; ++i) {
...
if (some_condition) { break _Time_; /* terminate the do-while loop */}
...
}
...
} while (thisCondition);

View file

@ -0,0 +1,25 @@
while (condition) {
...
if (someCondition) { continue; /* skip to beginning of this loop */ }
...
}
top: for (int 1 = 0; i < 10; ++i) {
...
middle: for (int j = 0; j < 10; ++j) {
...
bottom: for (int k = 0; k < 10; ++k) {
...
if (top_condition) { continue top; /* restart outer loop */ }
...
if (middle_condition) { continue middle; /* restart middle loop */ }
...
if (bottom_condition) { continue bottom; /* restart bottom loop */ }
...
if (bottom_condition) { continue; /* this will also restart bottom loop */ }
...
}
...
}
....
}

View file

@ -0,0 +1,5 @@
i = 0
while true do
i = i + 1
if i > 10 then break end
end

View file

@ -0,0 +1 @@
GOTO LABEL^ROUTINE

View file

@ -0,0 +1 @@
GOTO THERE

View file

@ -0,0 +1,2 @@
Read "Do you really wish to halt (Y/N)?",Q#1
IF Q="Y"!Q="y" HALT

View file

@ -0,0 +1 @@
JOB LABEL^ROUTINE

View file

@ -0,0 +1 @@
JOB THERE

View file

@ -0,0 +1 @@
JOB LABEL^ROUTINE

View file

@ -0,0 +1,2 @@
FOR I=1:1:1 QUIT:NoLoop DO YesLoop
QUIT Returnvalue

View file

@ -0,0 +1,4 @@
SET A="SET %=$INCREMENT(I)"
SET I=0
XECUTE A
WRITE I

View file

@ -0,0 +1,8 @@
/* goto */
block(..., label, ..., go(label), ...);
/* throw, which is like trapping errors, and can do non-local jumps to return a value */
catch(..., throw(value), ...);
/* error trapping */
errcatch(..., error("Bad luck!"), ...);

View file

@ -0,0 +1,7 @@
<?php
goto a;
echo 'Foo';
a:
echo 'Bar';
?>

View file

@ -0,0 +1,3 @@
FORK:
# some code
goto FORK;

View file

@ -0,0 +1,10 @@
# Search for an odd factor of a using brute force:
for i in range(n):
if (n%2) == 0:
continue
if (n%i) == 0:
result = i
break
else:
result = None
print "No odd factors found"

View file

@ -0,0 +1,13 @@
# Let's call our custom error "StupidError"; it inherits from the Exception class
class StupidError(Exception): pass
# Try it out.
try:
raise StupidError("Segfault") # here, we manually 'raise' the error within the try block
except StupidError, details: # 'details' is the StupidError object we create in the try block.
print 'Something stupid occurred:', details # so we access the value we had stored for it...
# Output :
# Something stupid occurred: Segfault

View file

@ -0,0 +1,20 @@
i = 101
for i in range(4): # loop 4 times
print "I will always be seen."
if i % 2 == 0:
continue # continue goes back to the loop beginning for a new iteration.
print "I'll only be seen every other time."
else:
print "Loop done"
# Output:
# I will always be seen.
# I will always be seen.
# I'll only be seen every other time.
# I will always be seen.
# I will always be seen.
# I'll only be seen every other time.
# Loop done
if(__name__ == "__main__"):
main()

View file

@ -0,0 +1,9 @@
class Quitting(Exception): pass
max = 10
with open("some_file") as myfile:
exit_counter = 0
for line in myfile:
exit_counter += 1
if exit_counter > max:
raise Quitting
print line,

View file

@ -0,0 +1 @@
class MyException(Exception): pass

View file

@ -0,0 +1,3 @@
class MyVirtual(object):
def __init__(self):
raise NotImplementedError

View file

@ -0,0 +1,6 @@
try:
temp = 0/0
# 'except' catches any errors that may have been raised between the code of 'try' and 'except'
except: # Note: catch all handler ... NOT RECOMMENDED
print "An error occurred."
# Output : "An error occurred"

View file

@ -0,0 +1,6 @@
try:
temp = 0/0
# here, 'except' catches a specific type of error raised within the try block.
except ZeroDivisionError:
print "You've divided by zero!"
# Output : "You've divided by zero!"

View file

@ -0,0 +1,11 @@
try:
temp = 0/0
except:
print "An error occurred."
# here, 'finally' executes when the try - except block ends, regardless of whether an error was raised or not
# useful in areas such as closing opened file streams in the try block whether they were successfully opened or not
finally:
print "End of 'try' block..."
# Output :
# An error occurred
# End of 'try' block...

View file

@ -0,0 +1,8 @@
try:
try:
pass
except (MyException1, MyOtherException):
pass
except SomeOtherException:
finally:
do_some_cleanup() # run in any case, whether any exceptions were thrown or not

View file

@ -0,0 +1,9 @@
try:
temp = 1/1 # not a division by zero error
except ZeroDivisionError: # so... it is not caught
print "You've divided by zero."
# here, 'else' executes when no exceptions are caught...
else:
print "No apparent error occurred."
# Output :
# No apparent error occurred.

View file

@ -0,0 +1,20 @@
i = 0
while 1: # infinite loop
try:
temp2 = 0/i # will raise a ZeroDivisionError first.
temp = math.sqrt(i)
break # 'break' will break out of the while loop
except ValueError: #
print "Imaginary Number! Breaking out of loop"
break # 'break' out of while loop
except ZeroDivisionError:
print "You've divided by zero. Decrementing i and continuing..."
i-=1 # we decrement i.
# we 'continue', everything within the try - except block will be executed again,
# this time however, ZeroDivisionError would not be raised again.
continue # Note that removing it, replacing it with 'pass' would perform the equivalent
# see below for a better example
# Output :
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop

View file

@ -0,0 +1,3 @@
exit
exit expression

View file

@ -0,0 +1,3 @@
return
return expression

View file

@ -0,0 +1,39 @@
signal on error
signal on failure
signal on halt
signal on lostdigits
signal on notready
signal on novalue
signal on syntax
signal off error
signal off failure
signal off halt
signal off lostdigits
signal off notready
signal off novalue
signal off syntax
signal on novalue
x=oopsay+1
novalue: say
say '*** error! ***'
say
say 'undefined REXX variable' condition("D")
say
say 'in line' sigl
say
say 'REXX source statement is:'
say sourceline(sigl)
say
exit 13

View file

@ -0,0 +1,22 @@
do j=1 to 10
say 'j=' j
if j>5 then leave
say 'negative j=' -j
end
say 'end of the DO loop for j.'
ouch=60
sum=0
do k=0 to 100 by 3
say 'k=' k
do m=1 to k
if m=ouch then leave k
sum=sum+m
end
end
say 'sum=' sum

View file

@ -0,0 +1,24 @@
sum=0
do j=1 to 1000
if j//3==0 | j//7==0 then iterate
sum=sum+j
end
/*shows sum of 1k numbers except those divisible by 3 or 7.*/
say 'sum='sum
numeric digits 5000
prod=0
do k=1 to 2000
do m=1 to k
if m>99 then iterate k
prod=prod*m
end
end
say 'prod=' prod

View file

@ -0,0 +1,18 @@
numeric digits 1000 /*prepare for some gihugeic numbers.*/
n=4
call factorial n
say n'!=' result
exit
factorial: parse arg x
!=1
do j=2 to x
!=!*j
end
return !

View file

@ -0,0 +1,25 @@
prod=1
a=7 /*or somesuch.*/
b=3 /* likewise. */
op='**' /*or whatever.*/
select
when op=='+' then r=a+b /*add. */
when op=='-' then r=a-b /*subtract. */
when op=='*' then do; r=a*b; prod=prod*r; end /*multiply.*/
when op=='*' then r=a*b /*multiply. */
when op=='/' & b\=0 then r=a/b /*divide. */
when op=='%' & b\=0 then r=a/b /*interger divide. */
when op=='//' & b\=0 then r=a/b /*modulus (remainder). */
when op=='||' then r=a||b /*concatenation. */
when op=='caw' then r=xyz(a,b) /*call the XYZ subroutine*/
otherwise r='[n/a]' /*signify not applicable.*/
end
say 'result for' a op b "=" r

View file

@ -0,0 +1,13 @@
begin
# some code that may raise an exception
rescue ExceptionClassA => a
# handle code
rescue ExceptionClassB, ExceptionClassC => b_or_c
# handle ...
rescue
# handle all other exceptions
else
# when no exception occurred, execute this code
ensure
# execute this code always
end

View file

@ -0,0 +1,3 @@
values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]

View file

@ -0,0 +1,17 @@
def some_method
# ...
if some_condition
throw :get_me_out_of_here
end
# ...
end
catch :get_me_out_of_here do
for ...
for ...
some_method
end
end
end
puts "continuing after catching the throw"

View file

@ -0,0 +1 @@
after 1000 {myroutine x}

View file

@ -0,0 +1 @@
after cancel myroutine

View file

@ -0,0 +1,8 @@
package require Tk
proc update {} {
.clockface configure -text [clock format [clock seconds]]
after 1000 update ; # call yourself in a second
}
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
update

View file

@ -0,0 +1,5 @@
if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
} else {
''... process $result ...''
}

View file

@ -0,0 +1,10 @@
try {
# Just a silly example...
set f [open $filename]
expr 1/0
string length [read $f]
} trap {ARITH DIVZERO} {} {
puts "divided by zero"
} finally {
close $f
}

View file

@ -0,0 +1,8 @@
proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
while {[gets $filechan line] != -1} {
uplevel 1 $code ; # Run supplied code in caller's scope
}
close $filechan
}

View file

@ -0,0 +1,3 @@
forfilelines myline mydata.txt {
puts [string length $myline]
}