REBOL Writing Functions

advertisement
REBOL
Writing Functions
Four ways to define functions


To define a function with parameters and local variables:
function spec locals actions
 Example: plus: function [x y] [sum] [sum: x + y
To define a function with parameters:
func spec actions


sum]
Example: plus: func [x y] [x + y]
To define a function with no parameters:
does actions
 Example: sing: does [print "do re mi"]

To define a function with local variables but no parameters:
has locals actions
 Example:
bigrand: has [x y] [x: random 10 y: random 10 max x y]
2
The “spec” and formal parameters

In both function spec locals actions and
func spec actions, the spec is a block


The first element of the spec may be a documentation string
The following elements are the names of formal parameters


There may be refinements (words prefixed by a backslash)



Each formal parameter may be followed by a block containing the
acceptable datatypes for that parameter
Inside the function, the refinement acts like a boolean variable
There may be local variables following /local
Example:

sum: func ["Sum or average" nums [block!]
/average /local total] [
total: 0
foreach num nums [total: total + num]
either average [total / (length? nums)][total]
]
3
Return values

The actions is a block of expressions to be evaluated

The value returned by a function is the value of the last
evaluated action

To return before reaching the end, use return value

To return without a value, use exit
4
Looking at functions



To see if a word is a function, use function? word
To see the source code of a function, use source functionName
To see the documentation string, use help functionName



>> sum: func ["Adds two numbers" x y] [x + y]
>> sum 3 5
== 8
>> help sum
USAGE:
SUM x y
DESCRIPTION:
Adds two numbers
SUM is a function value.
ARGUMENTS:
x -- (Type: any)
y -- (Type: any)
5
The End
6
Download