9.1 Simple procedure definitions
It is also possible to defined new commands, these are called procedures. Procedures are like functions, but they do not return a value. Also, they generally should have side-effects (mutation or I/O).
This split between functions and procedures is explicit because it simplifies maintenance. A programmer does not need to think about side-effects when they are working with functions. Likewise, since procedures do not return values, there is no mixing of behavior.
Here is a simple example of a procedure:
proc prompt (x:string) { write$ stdout, x; fflush stdout; } prompt "Input string: "; println$ readln$ stdin;
Road Runner beats Coyote!
Input string: Road Runner beats Coyote! Road Runner beats Coyote!
Here we notice:
- The
proc
binder introduces a procedure. - The procedure
prompt
issues a prompt onstdout
with afflush
to force the output to the device. - Procedures have side effects, here it is reading and writing to I/O.
- Procedures cannot return values
9.2 Anonymous procedure definitions
Procedures can be used anonymously, just like functions. The syntax is practically the same.
(proc (x:int) { println$ x; })
There's an even shorter version for situations when your procedure doesn't take any inputs:
{ println "Hello"; }
9.3 Iteration
Since a proc
cannot return a value, it can't be used in a map
like fun
functions do.
The equivalent operator for procedures is called iter
, which stands for iteration.
With it, instead of mapping from one value to another, we visit each input and do some action.
Here is an example:
var items = list(1,2,3); iter (proc (x:int) { println x; }) items;
1 2 3