REBOL Writing Functions Four ways to define functions
REBOL Writing Functions
Four ways to define functions n n To define a function with parameters and local variables: function spec locals actions n Example: plus: function [x y] [sum: x + y To define a function with parameters: func spec actions n n sum] Example: plus: func [x y] [x + y] To define a function with no parameters: does actions n Example: sing: does [print "do re mi"] n To define a function with local variables but no parameters: has locals actions n Example: bigrand: has [x y] [x: random 10 y: random 10 max x y] 2
The “spec” and formal parameters n In both function spec locals actions and func spec actions, the spec is a block n n The first element of the spec may be a documentation string The following elements are the names of formal parameters n n There may be refinements (words prefixed by a backslash) n n n 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: n sum: func ["Sum or average" nums [block!] /average /local total] [ total: 0 foreach nums [total: total + num] either average [total / (length? nums)][total] ] 3
Return values n n The actions is a block of expressions to be evaluated The value returned by a function is the value of the last evaluated action n To return before reaching the end, use return value n To return without a value, use exit 4
Looking at functions n n n To see if a word is a function, use function? word To see the source code of a function, use source function. Name To see the documentation string, use help function. Name n n n >> 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
- Slides: 6