Skip to content

procedure

Turtle Kitty edited this page Jan 29, 2016 · 1 revision

proc

Procedures are used to calculate. New procedures are created by the operator proc.

(def square (proc (x) (* x x)))
(square 3) -> 9

The proc operator can take a name before its formals. This is syntactic sugar for (def name (proc (args) ...).

(proc square (x) (* x x)) 
(square 5) -> 25

The _ operator can be used as a short way of generating one-argument procedures.

(def nums (list 1 2 3)) 
(nums.map (_ (* _ _))) -> (1 4 9)
(nums.map (_ _.to-text) -> ("1" "2" "3")

Procedures close over their current lexical environment.

Procedures have an implied (seq ...) for multiple bodies.

(proc foo (x) 
    (sys.print x)
    (+ x 23))

All procedures are variadic (rest) and can accept optional keyword parameters (opt).

(proc snazzer (x y)
    (if opt.snazz
        (list x y opt.snazz opt.snarf rest)
        (list x y rest)))

(snazzer 1 2) -> (1 2 ()) 
(snazzer 1 2 3) -> (1 2 (3))
(snazzer 1 2 3 4 5) -> (1 2 (3 4 5)) 
(snazzer 1 2 3 4 5 snazz: true)
    -> (1 2 true null (3 4 5)) 
(snazzer 1 2 3 4 5 snazz: true snarf: "SNARF!")
    -> (1 2 true "SNARF!" (3 4 5))

Sexy has tail call optimization; tail-recursive functions can recurse forever without blowing the stack.

(proc factorial (n)
    (proc fact (n acc)
        (if (= n 1)
            acc
            (fact (- n 1) (* n acc))))
    (fact n 1))

(factorial 20000)
    -> 18192063202303451348276417568664587660... (77300 more digits)

A procedure can abort its computation early with the return keyword.

(proc foo (x)
    (when (< x 10)
        return 'no-worries)
    ... some long and painful computation ...)

predicate

(proc? x)

(proc? +) -> true
(proc? 1) -> false

messages

x.type -> proc

x.to-bool -> true

x.arity -> number of formal arguments

x.formals -> a list of formal parameters

x.code -> textual description of the function

x.env -> the closure's lexical environment

λ

There is also a limited version of procedures identified by λ. These allow only one body expression (use a seq if you need more), and the dynamic variables opt, rest, and return are not bound for lambdas as they are for procedures. This makes them useful in creating new control structures to be used within procedures (see while and for).

((λ (x) (* x x)) 7) -> 49
Clone this wiki locally