Capabilities
examples/capabilities.sld:
;; Capabilities. A function writes only to the port it is given, so its
;; caller decides where the lines go.
(import
(snail core base)
(snail core io))
(define (total-cost (log OutputPort) (prices (List I64))) (→ I64)
(fold-left (lambda (total price)
(write-line log (string-append "adding " (show price)))
(+ total price))
0 prices))
;; A port is a record of the function that writes it, so a program makes
;; its own: this one keeps nothing.
(define (nowhere) (→ OutputPort)
(new OutputPort (write-string (lambda (text) (unit)))))
;; The same function, quiet or verbose, depending only on the port.
(define (main (out OutputPort)) (→ Unit)
(display out (total-cost (nowhere) (list 3 4 5)))
(newline out)
(display out (total-cost out (list 1 2)))
(newline out)
(unit))
It prints:
12
adding 1
adding 2
3
total-cost writes to the port it is given and to no other, so its caller
decides where the lines go: main hands it its own port, from the target,
or one of the program’s making that keeps nothing.
A callback does what it was made with. This function adds output around an action:
(define (announce (out OutputPort) (action (Fn → A))) (→ A) (∀ (A))
(write-line out "calling")
(action))
announce writes to the port it is given. What the call of action does
is not in announce’s signature or in action’s type: a closure that
captured a port writes to it, and one that captured none reaches nothing
of the host’s.
Capabilities covers this in full, and
suspension how a computation stops and resumes.