function

$

create function with given arguments and body


Parameters

function arguments :literal :block
         body :block

Attributes

import :block import/embed given list of symbols from current environment
export :block export given symbols to parent
memoize store results of function calls
inline execute function without scope

Returns

  • :function

Examples

copy
f: function [x][ x + 2 ] print f 10 ; 12 f: $[x][x+2] print f 10 ; 12

copy
multiply: function [x,y][ x * y ] print multiply 3 5 ; 15

copy
; forcing typed parameters addThem: function [ x :integer y :integer :floating ][ x + y ]

copy
; adding complete documentation for user function ; using data comments within the body addThem: function [ x :integer :floating y :integer :floating ][ ;; description: « takes two numbers and adds them up ;; options: [ ;; mul: :integer « also multiply by given number ;; ] ;; returns: :integer :floating ;; example: { ;; addThem 10 20 ;; addThem.mult:3 10 20 ;; } mult?: attr 'mult switch not? null? mult? -> return mult? * x + y -> return x + y ] info'addThem ; |-------------------------------------------------------------------------------- ; | addThem :function 0x10EF0E528 ; |-------------------------------------------------------------------------------- ; | takes two numbers and adds them up ; |-------------------------------------------------------------------------------- ; | usage addThem x :integer :floating ; | y :integer :floating ; | ; | options .mult :integer -> also multiply by given number ; | ; | returns :integer :floating ; |--------------------------------------------------------------------------------

copy
publicF: function .export:['x] [z][ print ["z =>" z] x: 5 ] publicF 10 ; z => 10 print x ; 5

copy
; memoization fib: $[x].memoize[ switch x<2 -> 1 -> (fib x-1) + (fib x-2) ] loop 1..25 [x][ print ["Fibonacci of" x "=" fib x] ]

Related