Presentation is loading. Please wait.

Presentation is loading. Please wait.

REBOL Writing Functions.

Similar presentations


Presentation on theme: "REBOL Writing Functions."— Presentation transcript:

1 REBOL Writing Functions

2 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 sum] To define a function with parameters: func spec actions 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]

3 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 Each formal parameter may be followed by a block containing the acceptable datatypes for that parameter There may be refinements (words prefixed by a backslash) 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: foreach num nums [total: total + num] either average [total / (length? nums)][total] ]

4 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

5 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)

6 The End


Download ppt "REBOL Writing Functions."

Similar presentations


Ads by Google