Non-destructive models describe results without treating every
variable as a changing memory cell. Lisp, Scheme, Prolog, and lazy
functional examples develop different approaches to binding,
composition, search, and interaction with the outside world.
Chapter Map
Lisp and S-expressions: evaluation, quoting, first-class functions,
lexical closures, and I/O
Scheme, continuations, and clean formatting conventions for
Lisp-like code
logic programming in Prolog: facts, rules, unification,
backtracking, and search control
lazy evaluation, sharing, and working with infinite data structures
in Hope
Detailed notes - 11: Non-destructive paradigms
1
earlier languages: program changes a state over time
functional examples were possible, but the languages mainly supported imperative programming
2
non-destructive languages: avoid changes to the execution environment
Lisp / Scheme allow assignment, but favour building new values
Prolog / Hope have no ordinary assignment
Prolog still has I/O and database changes as side effects
lazy Hope evaluates a value only when needed
-> expression side effects would have unpredictable timing
3
learning these models requires a different way of thinking
author values this flexibility even for later imperative work
11.1 Lisp and its S-expressions
Lisp represents both program forms and heterogeneous data through
S-expressions. Evaluation, first-class functions, and lexical closures
provide the core ideas, while mutation and application I/O show where
Common Lisp extends beyond pure functional programming.
11.1.1 A little history
Lisp grew from symbolic computation and an evaluator expressed in its
own data notation. Common Lisp and Scheme later developed distinct
specifications, binding conventions, and teaching traditions; the
chapter's implementation choices reflect that historical setting.
Detailed notes - 11.1.1: A little history
1
Lisp dates from the 1950s
among the languages discussed, only Fortran is older
both changed considerably during their subsequent development
2
McCarthy: symbolic expressions for artificial intelligence, from 1956
IPL suggested representing formulas with lists
attempted symbolic differentiation using FLPL in 1958
#include <stdio.h>
#include "tape.hpp"
#include "program.hpp"
enum {
start_state = 0,
halt_state = -1,
rule_fields = 5
};
enum read_status {
read_ok,
read_end,
read_error
};
static read_status read_rule(FILE *file, rule &r)
{
int fields = fscanf(file, " %d %c %c %c %d",
&r.state, &r.read, &r.write, &r.move, &r.next);
switch (fields) {
case rule_fields:
return read_ok;
case EOF:
return read_end;
default:
return read_error;
}
}
static bool valid_move(char move)
{
return move == 'L' || move == 'R' || move == 'S';
}
static bool read_program(FILE *file, Program &program)
{
rule r;
read_status status;
while ((status = read_rule(file, r)) == read_ok) {
if (!valid_move(r.move)) {
fprintf(stderr, "Invalid movement: %c\n", r.move);
return false;
}
program.Add(r);
}
if (status == read_error || program.Empty()) {
fprintf(stderr, "Invalid or empty rule file\n");
return false;
}
return true;
}
static bool load_program(const char *filename, Program &program)
{
FILE *file = fopen(filename, "r");
if (!file) {
perror(filename);
return false;
}
bool ok = read_program(file, program);
fclose(file);
return ok;
}
static bool run(const Program &program, Tape &tape)
{
int state = start_state;
while (state != halt_state) {
const rule *r = program.Find(state, tape.Read());
if (!r) {
fprintf(stderr, "No rule for state %d, symbol '%c'\n",
state, tape.Read());
return false;
}
tape.Write(r->write);
tape.Move(r->move);
state = r->next;
}
return true;
}
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: %s rules.txt input\n", argv[0]);
return 1;
}
Program program;
bool ok = load_program(argv[1], program);
if (!ok)
return 1;
Tape tape(argv[2]);
ok = run(program, tape);
if (!ok)
return 1;
tape.Print();
return 0;
}
11.1.2 SBCL, GCL and ECL
A REPL, script execution, native compilation, and standalone
distribution are separate capabilities. The book compares SBCL image
saving, GCL object loading, and ECL's C-based build path, including
implementation-specific startup and argument handling.
Detailed notes - 11.1.2: SBCL, GCL and ECL
1
Common Lisp implementations used in the book:
SBCL: Steel Bank Common Lisp
GCL: GNU Common Lisp
ECL: Embeddable Common Lisp
corresponding packages commonly use these lowercase names
2
Unix script: interpreter path and script-mode flag on the first line
SBCL: #!/usr/bin/sbcl --script
GCL: #!/usr/bin/gcl -f
ECL: #!/usr/bin/ecl -shell
body: (princ "Hello world!") followed by (terpri)
chmod +x myfile.lsp -> run ./myfile.lsp
3
shebang restrictions vary between Unix systems
book warns about short first-line limits and one optional argument
some systems require the interpreter to be a binary executable
Linux can also permit an interpreter script
4
REPL = read, evaluate, print, repeat
starting sbcl / gcl / ecl without a script enters this mode
5
load definitions before entering the REPL:
sbcl --noinform --load myfile.lsp
gcl -load myfile.lsp; ECL also uses -load
SBCL's --noinform suppresses its startup information
6
interactive editing differs between the implementations described
GCL uses GNU Readline for history / editing / completion
rlwrap supplies editing for SBCL / ECL
example: rlwrap sbcl --noinform --load myfile.lsp
wrapper does not automatically know the interpreter's symbols
7
rlwrap controls:
up / down: history; Ctrl-R: reverse search; Tab: completion
-c enables filename completion
-f can supply a file of words for completion
8
command-line arguments are implementation-specific
SBCL: *posix-argv*; GCL: si::*command-args*
both give a list beginning with the script name
echo: mapcar prints each element of (cdr argument-list)
ECL: (ext:command-args) includes interpreter and -shell first
#!/bin/sh
# nest.sh: scripts whose interpreter is another script, deeper and deeper
# s0 is run by /bin/sh, s1 by s0, s2 by s1, and so on
# usage: sh nest.sh
dir=$(mktemp -d)
cat > "$dir/s0" <<'EOF'
#!/bin/sh
line="/bin/sh ${0##*/}"
for a in "$@"; do
line="$line ${a##*/}"
done
echo "works: $line"
EOF
chmod +x "$dir/s0"
i=1
while [ $i -le 7 ]; do
printf '#!%s/s%d\n' "$dir" $((i - 1)) > "$dir/s$i"
chmod +x "$dir/s$i"
i=$((i + 1))
done
i=0
while [ $i -le 7 ]; do
printf 's%d: ' $i
"$dir/s$i" 2>&1 | sed "s|$dir/||g"
i=$((i + 1))
done
rm -r "$dir"
#!/bin/sh
# nest.sh: s1 has s0 as its interpreter, s2 has s1, and so on;
# s0 has /bin/echo, which prints the command line it receives
# usage: sh nest.sh
dir=$(mktemp -d)
cd "$dir" || exit 1
echo '#!/bin/echo' > s0
chmod +x s0
i=1
while [ $i -le 7 ]; do
echo "#!./s$((i - 1))" > s$i
chmod +x s$i
printf 's%d: ' $i
./s$i
i=$((i + 1))
done
rm -r "$dir"
11.1.3 S-expressions: a heterogeneous data
model
S-expressions combine atoms and pairs, with proper lists formed by
pair chains ending in nil. Symbols can serve as names or data, and
modern Lisp adds arrays, structures, and other values beyond this
introductory list model.
Detailed notes - 11.1.3: S-expressions: a heterogeneous data model
1
S-expressions represent both Lisp data and program forms
heterogeneous lists can contain different types and nested lists
2
S-expression = atom or dotted pair
literal atoms: numbers, characters, strings
characters: #\a, #\5, #\Space, #\Newline, #\Tab
3
numeric types can preserve more information than machine arithmetic
2/3 is one rational-number token, stored as numerator / denominator
#C(1 -2) represents a complex number
arbitrary-size integers avoid a fixed machine-word limit
4
symbols: named objects resembling identifiers in other languages
names may include punctuation: GO-JOHNNY-GO, *STDIN*, ==^==
ordinary Common Lisp input converts letters to uppercase
-> as21 / As21 / AS21 normally name the same symbol
5
symbols can be names and ordinary data values
useful as distinct tags, somewhat like enumeration constants
a file-summing function may return a number on success
exceptional results can be OPEN_ERROR, WRONG_DATA or EMPTY
6
nil = false = empty list
() is another notation for the same object
nil evaluates to itself
7
atom means any object that is not a dotted pair
does not necessarily mean a small or indivisible implementation
8
dotted pair: (left . right), with arbitrary S-expressions in both parts
whitespace must separate the dot from surrounding tokens
each part can be understood as a pointer to another object
objects can be shared by several pairs
changing a shared (1 . 2) affects every structure containing it
9
proper list: chain of pairs ending in nil
each left part holds an element; right part points to the rest
(1 . (2 . (3 . ()))) = (1 2 3)
elements may themselves be lists / dotted pairs / other atoms
non-nil ending -> improper list: (1 2 3 . 4)
10
modern Lisp also provides arrays, structures and hash tables
heterogeneous values can be used as hash-table keys / values
Common Lisp Object System adds object-oriented facilities
11
these additional objects can occur inside S-expressions
arrays / structures / objects are atoms in the pair-versus-atom classification, even when they contain further objects
12
book omits most non-list structures
they add facilities already encountered in earlier paradigms
; sexpr.lsp: data and programs are both S-expressions
; sbcl --script sexpr.lsp
; 1. a heterogeneous list: a number, a string, a symbol, a list, a float
(defvar mix (list 1 "two" 'three (list 4 5) 6.5))
(format t "mix = ~s~%" mix)
(format t "types = ~s~%" (mapcar #'type-of mix))
(format t "4th elem. = ~s, its length ~a~%" (fourth mix) (length (fourth mix)))
; 2. a piece of program, quoted, is just a list
(defvar expr '(+ 1 2))
(format t "~%expr = ~s~%" expr)
(format t "first = ~s (a ~a)~%" (first expr) (type-of (first expr)))
(format t "rest = ~s~%" (rest expr))
(format t "evaluated = ~s~%" (eval expr))
; 3. a function definition is a list too
(defvar def '(defun cube (x) (* x x x)))
(format t "~%def = ~s~%" def)
(format t "length = ~a, first = ~s~%" (length def) (first def))
(eval def) ; run the list as a program
(format t "(cube 3) = ~a~%" (cube 3))
; 4. build a program out of data, then run it
(defvar built (list '* 6 7))
(format t "~%built = ~s -> ~a~%" built (eval built))
#!/usr/bin/sbcl --script
(defvar p (cons 1 2)) ; the pair (1 . 2)
(defvar foo (cons "Foo" p)) ; ("Foo" . (1 . 2))
(defvar bar (cons "Bar" p)) ; ("Bar" . (1 . 2))
(format t "foo = ~s~%bar = ~s~%" foo bar)
(format t "the same pair: ~a~%" (eq (cdr foo) (cdr bar)))
(setf (car (cdr foo)) 100) ; change it through foo only
(format t "after the change through foo:~%")
(format t "foo = ~s~%bar = ~s~%" foo bar)
11.1.4 Evaluating S-expressions
Evaluation treats self-evaluating data, symbol lookup, ordinary
calls, macros, and special forms differently. Quote preserves a form as
data, conditional forms control evaluation, and equality predicates
distinguish identity, numeric details, and recursive structure.
Detailed notes - 11.1.4: Evaluating S-expressions
1
evaluation gives S-expressions computational meaning
result may depend on the environment in which evaluation occurs
2
numbers, characters and strings evaluate to themselves
(defun f (x)
(+ x 1)
)
(defun g (x)
(- x 1)
)
(defun h (x)
(cond
((> x 0) (f x))
(t (g (- x)))
)
)
11.1.5 User-defined functions
defun installs a named function whose parameters receive argument
bindings. Recursive list length illustrates base cases and invalid
inputs, while an accumulator changes the recursive call into a tail
call.
Detailed notes - 11.1.5: User-defined functions
1
Lisp program: sequence of top-level forms
evaluated in order; many normally define functions
2
defun: name, parameter list, then body forms
arguments bind the parameter names during a call
last body form supplies the function's result
sqe-discrim(a,b,c): (- (* b b) (* 4 a c)) -> b*b - 4*a*c
3
defun has a side effect
associates the function name with a function object
association persists after the defining form finishes
4
recursive list length:
empty list -> 0; otherwise -> 1 + length(cdr list)
null base case fails on an improper list's final atom
atom base case counts cons cells and stops at any atomic tail
either if or cond can express the two alternatives
5
length2 distinguishes invalid atomic input
nil -> 0; other standalone atom -> nil
cons with an atomic cdr -> 1
otherwise -> 1 + length2(cdr list)
cond separates normal, base and exceptional cases
6
recursion is central to Lisp programming
tail-call optimization is especially useful for recursive loops
availability depends on the implementation / compilation settings
7
accumulator makes list-length recursion a tail call
wrapper handles nil / atomic input
helper starts with len = 1, advances cdr and increments len
no addition remains after the recursive call
reversing a list uses the same accumulator technique
-> move each car to the front of the accumulated result
-> (1 2 3), () -> (2 3), (1) -> (3), (2 1)
-> (), (3 2 1): return the accumulated list
Section test (1 file) - 11.1.5: User-defined functions
Binding a new parameter differs from overwriting existing state.
Common Lisp also permits variable assignment and pair mutation, whose
effects can spread through shared list tails; generalized places provide
a uniform assignment notation.
Detailed notes - 11.1.6: Destructive functions
1
destructive operation = operation with an observable modifying effect
examples include assignment and input / output
2
binding a new function parameter is different from assignment
establishes the initial value of a newly created binding
that binding disappears after its lifetime ends
3
defun changes the function associated with a name
normally definitions run before the main computation
Lisp also permits reassignment and changes to existing structures
4
setq assigns a value to a variable
variable name is not evaluated; value expression is evaluated
(setq x 25), then (setq x (+ x 1)) -> x is 26
5
quoting a name alone does not reproduce setq's behaviour
lexical binding matters; later sections explain the distinction
6
setq can contain several name / value pairs, processed in order
psetq first evaluates all values, then performs assignments
(psetq x y y x) swaps the old values
7
declare global variables explicitly with defvar
(defvar *myglobvar* 100)
surrounding asterisks are a naming convention
book's SBCL warns about undeclared globals
8
defvar also makes the name special / dynamically bound
more than a declaration of storage or an initial value
9
rplaca / rplacd replace a pair's car / cdr
starting with mutable list (1 2 3):
-> replace first car with 10
-> replace second cdr with 30
-> resulting structure: (10 2 . 30)
variable still points to the same first cons
use newly constructed lists for mutation; Common Lisp quoted literal data must not be destructively modified
10
changing a final cdr can form a cycle
last cons of (1 2 3) points back to the first cons
traversal no longer reaches nil
an unaware printer / traversal can run indefinitely
11
shared tails make mutations visible through several variables
a = (1 2 3 4); b = cons(10, cdr(a)) -> (10 2 3 4)
both share the cons cells holding 2, 3 and 4
setting the second cons's cdr to nil changes a to (1 2)
-> b simultaneously becomes (10 2)
12
copying the list spine avoids sharing those cons cells
recurse over cdr and cons each existing car onto the copied tail
Common Lisp provides copy-list
nested objects in the cars are still shared
13
setf assigns through generalized places
(setf (car x) v) changes a car
(setf x y) assigns a variable
(setf (aref arr 3) value) changes an array element
(setf (char str 4) #\u) changes a string character
also supports fields, hash-table entries and function bindings
setting (symbol-function 'car1) to #'car gives another name for that function object
14
setf implementation is separate from its uniform surface notation
author compares InteLib's location references with Common Lisp
Common Lisp supports setter functions named (setf accessor)
author's criticisms concern this implementation design
15
Common Lisp also specifies built-in setf places / expansions
book discusses implementation differences and code-size concerns
these are the author's arguments, not universal runtime costs
16
Lisp permits functional programming but does not enforce purity
author identifies heterogeneous S-expressions as its central idea
destructive operations remain available throughout the language
Section test (1 file) - 11.1.6: Destructive functions
eval gives runtime-constructed S-expressions computational meaning,
while read and intern connect text with forms and symbols. This
flexibility complicates static analysis and can coexist with native
compilation and substantial runtime support.
Detailed notes - 11.1.7: The eval function
1
eval evaluates an S-expression supplied as data
ordinary call evaluation first computes eval's argument
eval then interprets that resulting value as a form
the expression can be constructed while the program runs
it may contain defun or changes to function bindings
-> running program can construct and install new behaviour
3
intern finds / creates a symbol from its textual name
returns the existing interned symbol when one already exists
together with eval, permits construction of arbitrary Lisp forms
4
unrestricted runtime code construction complicates static analysis
in general, cannot predict every symbol / operation it will use
simple restricted cases can still be analysed
5
read parses textual S-expressions and interns their symbols
ordinary readable structures can arrive from files / input
unrestricted evaluation of such input needs runtime language facilities; static source alone does not determine all behaviour
6
book relates this flexibility to the size of Lisp runtime images
SBCL / GCL examples include runtime facilities in the executable
ECL examples depend on shared runtime libraries
7
SBCL compiles Lisp functions to native machine code
includes functions entered through the REPL
book disputes calling this compilation because runtime support remains; that is the author's terminology, not a denial that native-code compilation takes place
8
generated native code needs executable memory
original executable text and ordinary data have access protections
operating-system facilities such as mmap can allocate suitable memory, subject to the system's protection rules
9
author argues that execution speed is not the only relevant distinction
also considers runtime size / dependence on the language system
10
book postpones its wider interpretation-versus-compilation discussion
11.1.8 Functions as objects
First-class functions can be passed, returned, and created by lambda,
enabling mapcar and function-producing functions. Common Lisp
distinguishes function and variable bindings, with funcall and apply
providing explicit application of function values.
Detailed notes - 11.1.8: Functions as objects
1
first-class function: can be passed, returned and created at runtime
function accepting functions -> higher-order function
2
(symbol-function 'cons) obtains the function bound to CONS
printed representation differs between implementations
3
many Lisp data structures can be printed and read back
textual S-expressions provide a portable representation of data
4
printed function objects generally cannot be read back into functions
#<...> marks an unreadable object representation
5
function obtains the function denoted by its unevaluated argument
(function cons) obtains cons
respects lexical function bindings unlike symbol-function
can also construct a function from a lambda expression
6
#' is shorthand for function
#'cons = (function cons); #'+ obtains addition
7
funcall receives arguments individually; apply receives a final list
(funcall #'+ 1 20 300 4000 50000) -> 54321
(apply #'+ '(1 20 300 4000 50000)) -> 54321
apply permits a number of arguments determined at runtime
8
Common Lisp also accepts a symbol as a function designator
higher-order functions can resolve its function binding
author chooses explicit function objects in the examples
9
mapcar applies a function to corresponding list elements
Dynamic binding can make a passed or returned function use the
caller's names instead of its intended environment. Lexical closures
retain the defining bindings, including shared mutable bindings that
several closures can access together.
Detailed notes - 11.1.9: The funarg problem and lexical binding
1
early Lisp stored a symbol's current value in the symbol itself
symbol-value still accesses a symbol's dynamic value
lexical variable lookup need not return that value
2
simple local-variable implementation:
save old symbol value; install parameter / local value
execute body; restore old value on return
3
this is dynamic binding
value depends on the active call chain
book discusses its historical use and resulting surprises
4
make-adder(thevar) returns a function adding thevar
global thevar = 100; create plus5 with make-adder(5)
dynamic binding: (funcall plus5 10) returns 110, not 15
declaring thevar with defvar reproduces the special binding case
5
why 110: the temporary binding to 5 ended with make-adder
later free reference to thevar finds restored value 100
lambda's own x parameter still correctly receives 10
6
without an outer value, the returned function encounters an unbound name
restoration includes restoring the absence of a value
7
upward funarg problem: returned function loses its intended environment
downward variant: pass the function while its creator is active
sample(thevar) passes lambda(x) = x + thevar and 1000 to f2
f2 itself names its second parameter thevar
8
dynamic binding in f2 shadows sample's intended value 7 with 1000
lambda sees 1000; adds it to its argument 1000 -> 2000
intended lexical result: 1000 + 7 -> 1007
9
book proposes trying both modes in separate interpreter sessions
ordinary lexical variable -> 1007
defvar makes thevar special -> 2000
10
downward problem exposes accidental dependence on a caller's names
renaming f2's local parameter can change another function's result
banning free variables would also remove useful higher-order code
11
lexical binding resolves these examples
Common Lisp normally binds ordinary local variables lexically
special declarations retain dynamic binding where requested
12
conceptual lexical environment: name / binding entries plus parent link
search current environment, then enclosing environments
inner binding shadows an outer binding with the same name
13
environment tables describe semantics, not required implementation
compilers / interpreters can resolve access more efficiently
14
creating a local binding need not overwrite a symbol's dynamic value
add a distinct binding to the local environment
15
setq respects the active lexical binding
updates that binding rather than the symbol's dynamic value slot
16
var-values(var) returns (cons var (symbol-value 'var))
lexical argument "local", dynamic value "global"
-> ("local" . "global")
declaring var special would change what this example demonstrates
17
closure = function code together with its lexical environment
preserves bindings available where the function was created
top-level functions can have no captured local bindings
18
calling a closure uses its captured environment
parameter bindings belong to a new environment for that call
caller's unrelated lexical locals do not become visible
special operators can introduce / control binding environments
19
macro expansion code has its own environment
the generated form is subsequently processed at the use site
20
make-adder(33) captures a binding of thevar to 33
applying the closure to 27 creates x = 27
x found locally, thevar in captured environment -> 60
21
ordinary functions cannot evaluate arguments in a caller's lexical scope
that scope is not implicitly passed to the callee
22
Common Lisp eval does not receive the caller's lexical environment
demo-eval-symb(x) = (eval 'x) ignores the lexical parameter
uses the dynamic / global x, or reports it unbound
23
set receives an evaluated symbol and changes its dynamic value
cannot discover / modify a caller's lexical binding by name
24
let introduces local bindings and evaluates body forms in their scope
binding specifications: name or (name initial-expression)
omitted initializer gives nil in Common Lisp
result is the last body form's value
25
let example computes sum and product in one traversal
initialize s = 0, p = 1
mapped lambda updates both bindings for each list element
return (cons s p)
let initializers run in the outer environment
-> newly introduced variables are unavailable to one another
26
let* introduces bindings sequentially
later initializer can use a binding introduced earlier
27
flet / macrolet introduce local functions / macros
book does not develop these facilities further
28
closures capture bindings, not separate copies of their current values
several closures can share the same mutable binding
A nested routine needs both code and access to its enclosing
activation. Passing it downward can keep that environment alive, but
returning a GNU C nested-function pointer leaves stack-based context
invalid after the creator returns.
Detailed notes - 11.1.10: The funarg problem in other languages
1
funarg problems are not specific to Lisp
arise with callable values and nested functions referring to an enclosing environment whose lifetime may end
2
functional-language implementations account for captured bindings
variable representation need not be merely a stack location
3
traditional Pascal / C variables map closely to memory locations
globals in persistent storage; ordinary locals in stack frames
#include <stdio.h>
void sumprod(int *vec, int n, int *sum, int *prod)
{
int accum;
int plus(int a) { return accum + a; }
int times(int a) { return accum * a; }
void reduce(int *vec, int len, int (*op)(int))
{
if(!len)
return;
accum = op(*vec);
reduce(vec+1, len-1, op);
}
accum = 0; reduce(vec, n, &plus); *sum = accum;
accum = 1; reduce(vec, n, ×); *prod = accum;
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
int len = sizeof(a)/sizeof(*a);
int sum, prod;
sumprod(a, len, &sum, &prod);
printf("%d %d\n", sum, prod);
return 0;
}
11.1.11 Reducing lists
First-class functions make folds reusable list-building tools as well
as arithmetic reductions. Right-folding cons copies a list spine,
left-folding reversed cons arguments reverses it, and suitable combiners
can filter elements.
Detailed notes - 11.1.11: Reducing lists
1
folds become especially expressive with first-class functions
Lisp examples build on the earlier C / C++ reduction examples
2
lreduce(fun,lst,init): combine accumulator with car, recurse on cdr
(defun lreduce (fun lst init)
(cond
((null lst) init)
(t
(let ((next (funcall fun init (car lst))))
(lreduce fun (cdr lst) next)
)
)
)
)
(defun rreduce (fun lst init)
(cond
((null lst) init)
(t (funcall fun (car lst) (rreduce fun (cdr lst) init)))
)
)
(defun max_in_list (lst)
(lreduce #'(lambda (x y) (if (< x y) y x)) (cdr lst) (car lst))
)
(defun ins2list (i list)
(cond
((null list) (cons i ()))
((< i (car list)) (cons i list))
(t (cons (car list) (ins2list i (cdr list))))
)
)
(defun redsort (lst) (rreduce #'ins2list lst ()))
(defun redsort2 (lst)
(lreduce #'(lambda (ls el) (ins2list el ls)) lst ())
)
(defun redmap (fun lst)
(rreduce #'(lambda (x res) (cons (funcall fun x) res)) lst ())
)
(defun select (lst pred)
(rreduce
#'(lambda (x ls) (if (funcall pred x) (cons x ls) ls))
lst ()
)
)
11.1.12 The burden of older paradigms
Older Lisp facilities preserve symbols as both identifiers and
textual data, including escaped names and property lists. The author
argues that separating program names from user-facing text makes the
intended roles clearer.
Detailed notes - 11.1.12: The burden of older paradigms
1
early Lisp used symbols for words and lists of symbols for phrases
separate string objects were absent
author links this to a period when users were often programmers
2
later Lisp added strings but retained escaped symbol names
ordinary John becomes JOHN
|John| preserves mixed case and denotes a different symbol
vertical bars also permit spaces / punctuation within the name
3
symbol-name returns a symbol's name as a string
intern finds / creates a symbol from a string
4
author argues for separating program identifiers from user-facing text
renaming internal variables should not change visible behaviour
criticizes using symbols as a substitute for ordinary strings
5
symbol property lists are another older facility retained in Lisp
author's broader point concerns inherited programming habits
age alone does not change the semantics of the available features
11.1.13 Features the author would rather
omit
The author criticizes specification size, elaborate parameter
conventions, and an extensive loop sublanguage in light of his
preference for small application runtimes. These are design judgments
about complexity and distribution, not limits on Lisp's core ideas.
Detailed notes - 11.1.13: Features the author would rather omit
1
author criticizes Common Lisp's large specification
rejects the assumption that adding features has no cost
2
large libraries could in principle be modular
include only needed functions / symbols in an application
author favours implementations that can be reduced this way
3
general lambda lists add several parameter conventions
&optional: optional arguments
&rest: remaining arguments collected into a list
&key: keyword arguments; &aux: local auxiliary bindings
declarations can provide additional information to a compiler
4
these conventions complicate parsing and function application
unrestricted runtime eval can encounter them in generated code
author's concern: supporting unused possibilities still costs space
5
coerce takes a value and a type specifier
type can be a symbol such as string / float or a compound list
author criticizes coupling runtime facilities to many type symbols
6
loop provides an extensive iteration sublanguage
example combines bounds, stopping condition, collection and output
for / from / to / while / collect / do / when / finally guide it
author prefers smaller constructs for these jobs
7
author's main criticism: the specification does not promise a minimal runtime containing only facilities a particular application needs
8
author also objects to needing additional concepts for basic I/O
next section illustrates keyword arguments and condition handling
11.1.14 Input and output
Common Lisp distinguishes readable object printing from plain text
and exposes streams, EOF handling, file policies, and conditions. The
line-length example combines application-level error handling with
with-open-file so exceptional exits still close the file.
Detailed notes - 11.1.14: Input and output
1
I/O is necessary for complete applications
book uses this section to explain facilities and criticize their interfaces from the author's perspective
2
stream model: input / output operations can succeed, end or fail
EOF is an ordinary input state
applications need control over recoverable errors and diagnostics
3
Lisp's early I/O predates the later file / user-interface conventions
author traces some present interfaces to that history
4
input calls offer explicit EOF handling
specify stream, false eof-error-p, then value to return at EOF
otherwise EOF signals a condition
5
open appears with filesystem operations in the reference manual
accepts filename and keywords controlling stream creation
6
keyword arguments are needed to select output and other modes
condition handlers allow the application to handle failures
7
read parses Lisp syntax, which may be unsuitable for ordinary input
users asked for numbers should not need to understand Lisp forms
author distinguishes a programmer interface from a user interface
#!/usr/bin/sbcl --script
(defun main (len)
(let ((c (read-char t nil nil)))
(cond
((eq c nil) t)
((eq c #\Newline) (prin1 len) (terpri) (main 0))
(t (main (+ 1 len)))
)
)
)
(main 0)
11.1.15 A discouraging conclusion
The author's negative verdict concerns the implementations and
application-control requirements he examined. He still values Lisp's
core concepts and uses that tension to distinguish a programming model
from its practical delivery tools.
Detailed notes - 11.1.15: A discouraging conclusion
1
author judges the Common Lisp implementations discussed unsuitable for his preferred practical and teaching use
this is the author's broad assessment based on the preceding tests
2
author still values Lisp's core ideas
hopes for smaller implementations with less inherited complexity
3
principle proposed: application behaviour should be under the programmer's control through the program's source
motivates criticism of imposed diagnostics and runtime behaviour
11.2 Scheme: Lisp, with differences
Scheme retains Lisp's list notation and functional ideas while using
a smaller core and different evaluation conventions. The comparison
focuses on bindings, function application, proper tail calls, I/O, and
continuations.
Detailed notes - 11.2: Scheme: Lisp, with differences
repeats his preference for the smaller Scheme reports
2
many Lisp concepts carry over directly
discussion concentrates on the differences
11.2.1 Chicken Scheme
Chicken offers interpreter and compiler workflows, compiling through
generated C. The book's script modes, startup calls, imports, and
executable dependencies vary by implementation version, so source
execution and packaged application startup remain distinct concerns.
Detailed notes - 11.2.1: Chicken Scheme
1
book uses Chicken as its example Scheme implementation
2
tools: csi = interpreter; csc = compiler driver
book's Debian-family package name: chicken-bin
3
Chicken compiles Scheme through generated C
csc runs the Scheme compiler and then the C compiler
intermediate C is intended for compilation, not hand maintenance
4
Chicken's normal symbol handling is case-sensitive
book describes -i for case-insensitive input
this discussion concerns the versions used in the book
5
csi without arguments enters a REPL
rlwrap adds command-line editing
file arguments load definitions before entering the REPL
(load "myfile.scm") or REPL command ,l also loads a file
6
script mode: #!/usr/bin/csi -s
(display "Hello, world!\n") prints a greeting and newline
csc can compile the same script source
command-line-arguments returns arguments without program name
program-name retrieves that name separately
7
Chicken 5 requires imports for facilities that Chicken 4 exposed directly
Scheme separates false from the empty list and evaluates the operator
position as an ordinary expression, so function values need no separate
funcall. Lexical bindings, proper tail calls, and a compact definition
model shape its functional style.
Detailed notes - 11.2.2: Visible differences from traditional Lisp
(define (quad-eq a b c throw)
(if (= a 0) (throw 'NotAQuadraticEq))
(let ((discrim (- (* b b) (* 4 a c))))
(if (< discrim 0) (throw 'NoRealRoots))
(let
(
(mb2a (/ (- b) (* 2 a)))
(dq2a (/ (sqrt discrim) (* 2 a)))
)
(list (- mb2a dq2a) (+ mb2a dq2a))
)
)
)
11.2.3 Input and output in Scheme
Scheme I/O uses ports, character operations, and distinct readable
versus display output. The book's file-processing example relies on
Chicken condition handling, where a handler for the discussed
non-continuable failures must escape rather than return normally.
Detailed notes - 11.2.3: Input and output in Scheme
1
display prints an object; newline writes a line break
default destination is current output
2
write prints Scheme-readable notation
strings retain quotation marks; characters use #\... notation
display writes string contents / actual characters
read parses Scheme data; author advises against using it as an ordinary user-input parser without suitable error handling
3
read-char returns a character or an EOF object
eof-object? recognizes EOF
no extra argument is needed to treat EOF as ordinary input
4
write-char outputs a character directly
book distinguishes primitive operations from library procedures
5
peek-char observes the next character without consuming it
char-ready? tests whether input can proceed immediately
book notes limits of Chicken's terminal behaviour in its version
6
R5RS leaves aspects of file-error handling / existing output files insufficiently specified for the author's desired application interface
7
Chicken provides condition-handling facilities
usable to intercept failures instead of exposing default handling
8
Scheme calls I/O streams ports
input and output ports represent the corresponding directions
9
current-input-port / current-output-port are zero-argument procedures
Chicken also supplies current-error-port for diagnostics
example: (display "Error\n" (current-error-port))
10
author comments on the word current and changing these ports
parameterized current-port facilities depend on Scheme version / implementation; this passage reports his investigation
11
an explicit port is an optional I/O argument
only argument for newline / read-char
second argument for display / write / write-char
12
open-input-file / open-output-file take a filename string
return an opened port on success
failure signals a condition rather than returning a normal port
13
close-input-port / close-output-port close the corresponding port
14
with-exception-handler receives two procedures
handler: one argument, the condition object
thunk: zero arguments, performs protected computation
handler is active while that computation runs
15
for the non-continuable errors discussed, handler must escape
simply returning can cause another exception
example reports the condition and calls (exit 1)
continuation-based escape is another option
condition->list exposes implementation-specific condition data
16
worked script again prints input-line lengths
#!/usr/bin/csi -s also permits compilation by csc
17
Chicken 5 imports condition and process-context modules
do_it reads characters and tests eof-object? / newline
no filename -> use current-input-port
filename -> open, process, close input port
handler writes diagnostic information to current-error-port and exits with status 1
example does not print a final unterminated line
author suggests C modules for OS-facing work when Scheme's portable / implementation-specific interfaces are insufficient
Book example (1 file) - 11.2.3: Input and output in Scheme
Book exampleBook example: strlens_file.scmIn catalog
#!/usr/bin/csi -s
; uncomment for Chicken 5.* (and later?)
; (import (chicken process-context))
; (import (chicken condition))
(define (do_it port len)
(let ((c (read-char port)))
(cond
((eof-object? c) #t)
((eqv? c #\newline) (display len) (newline) (do_it port 0))
(else (do_it port (+ 1 len)))
)
)
)
(with-exception-handler
(lambda (ex)
(write (condition->list ex) (current-error-port))
(newline (current-error-port))
(display "something wrong (failed to open the file?)\n"
(current-error-port))
(exit 1) ; without this, endless loop occurs
)
(lambda ()
(let ((args (command-line-arguments)))
(if (null? args)
(do_it (current-input-port) 0)
(let ((port (open-input-file (car args))))
(do_it port 0)
(close-input-port port)
)
)
)
)
)
11.2.4 Continuations
A continuation represents the remaining computation and accepts the
value that computation awaits. call/cc captures it as a reusable control
object, enabling early exits, exception-like transfers, coroutines, and
other control arrangements beyond ordinary returns.
Detailed notes - 11.2.4: Continuations
1
continuation = the remaining computation at a particular point
begin by considering what happens after a function returns
2
caller uses the result, completes its work and returns to its caller
continuation represents that entire pending chain
3
remaining computation depends on the value supplied to it
4
ordinary call stacks illustrate a possible representation
return addresses and saved activation information describe pending work, although implementation needs more than code alone
5
Scheme need not represent this using an ordinary hardware stack
semantic requirement is preserving the pending computation
6
captured continuations are first-class objects
can be stored, passed and invoked like procedures
7
invocation supplies the value expected at the captured point
substitutes that value for the result being awaited there
8
captured continuation can survive beyond the original call
invoking it abandons the current continuation and resumes the saved control context with the supplied value
does not undo assignments, I/O or other completed side effects
9
book introduces concrete capture / invocation examples next
10
call-with-current-continuation, commonly call/cc
accepts a procedure of one argument
passes that procedure the current continuation
11
(call/cc (lambda (cc) ...)) binds the captured continuation to cc
captures the continuation of this call/cc expression
12
(cc x) makes the saved call/cc expression deliver x
resumes the work that was waiting for its result
13
the supplied procedure can also return normally
(call/cc (lambda (cc) 25)) -> 25
(call/cc (lambda (cc) (cc 25))) -> 25 by continuation invocation
second form abandons the lambda's current continuation
14
these minimal examples illustrate control flow rather than useful work
15
continuations can express early returns, exception-like escapes, coroutines and other control arrangements
16
early exit: bind the continuation to a name such as return
enclose the computation inside call/cc and lambda
(return value) immediately supplies the enclosing result
return is an ordinary parameter name here
17
search / exception examples:
search scans with for-each; first matching element invokes return
exhausted list -> #f in the first search implementation
traverse can accept that continuation directly as its callback
-> first successful callback escapes all intervening calls
-> search2 needs an explicit fallback if a #f miss is required
quad-eq(a,b,c,throw) checks exceptional cases
-> a = 0: throw 'NotAQuadraticEq
-> negative discriminant: throw 'NoRealRoots
-> otherwise compute and return the two real roots
18
call/cc receives either normal roots or the thrown tag
outer let binds the outcome; cond selects a handler
pass throw explicitly through intermediate functions
normal results stay local; exceptional escape skips all those calls
19
this exception-like control transfer needs no object-oriented mechanism
20
right-now returns its own current continuation
(call/cc (lambda (cc) (cc cc)))
continuation is both invoked object and supplied value
21
go-when invokes a saved continuation with itself as argument
re-enters the saved point while retaining the same continuation
greeting followed by go-when -> repeated greeting
outer mutable counter starts at 5 and decreases on each pass
-> stop invoking when counter reaches 0 -> five greetings
counter changes persist across re-entry
22
further applications include coroutines, backtracking and generators
book points to Matt Might's worked continuation examples
Continuation-passing style supplies the next computation as an
explicit function argument. Nested continuations express the
intermediate steps of a calculation, and compilers can use that form to
organize control and memory management.
book describes Chicken's Scheme-to-C implementation technique
generated calls grow a stack-based allocation area
collection copies reachable objects onward and resets that area
this is a particular implementation strategy, not Scheme semantics
4
John Reynolds's historical account surveys discoveries of continuations
links explicit continuation passing with language implementation
11.3 Formatting Lisp-like code
Indentation should reveal nested forms and distinguish binding lists
from bodies. The author prefers fixed indentation and separately aligned
closing parentheses, presenting an alternative style rather than a
requirement of Lisp syntax.
Detailed notes - 11.3: Formatting Lisp-like code
1
indentation makes nested lists readable
author contrasts his fixed-indent style with argument alignment
traditional alignment can make each indentation step depend on the operator name's length
2
function definitions conventionally keep a recognizable header
name / parameters together; body starts on the following line
3
traditional Lisp style groups closing parentheses at the end
author prefers making each enclosing level visible
a close-all marker, such as historical muLISP's ], hides mismatches
4
book's alternative: fixed indentation and separately aligned closings
break a long form after its operator
indent each nested level by the same amount
place its closing parenthesis under the construct's start
5
prefix notation such as quote / #' belongs to the construct
align the closing parenthesis under that prefix, in this style
lambda keeps its parameter list with its header, like defun
6
let needs special care because bindings and body have different roles
short binding list can stay on the header line
long binding list gets its own indented block
optional ;; after its closing parenthesis marks the body boundary
author compares two layouts; these are style preferences
11.4 Logic and declarative programming
Logic programming defines relations and rules, then asks for values
satisfying a query. Prolog supports this declarative view, but its
operational search behavior remains essential for understanding
termination, answer order, and effects.
Detailed notes - 11.4: Logic and declarative programming
1
logic programming describes predicates / rules and asks for solutions
declarative programming states properties of the desired result
leaves the method of finding that result to the implementation
2
logic is one way to write declarative specifications
Prolog / Datalog combine the approaches
book contrasts SQL's declarative model with this logic vocabulary
3
earlier overview supplied introductory examples
following sections develop the operational details
11.4.1 Prolog and its history
Prolog combines logical relations with an executable search
procedure, historically implemented through binding and backtracking
machinery. Depth-first clause order can affect termination, so the full
language cannot always be understood from logical meaning alone.
Detailed notes - 11.4.1: Prolog and its history
1
Prolog emerged in Colmerauer's French research group
Colmerauer and Roussel produced an early implementation in 1972
2
Planner combined Lisp with logical inference ideas
book identifies it as an influence on Prolog
3
full Prolog has effects and control constructs beyond pure logic
solution order matters when search spaces are infinite
depth-first search can remain on one infinite branch
4
pure definite-clause Prolog is described through SLD resolution
author emphasizes operational search and binding environments
his criticism concerns explaining the whole language solely as formal logical inference
5
procedural semantics describe what the solver actually does
clause / goal order; alternative order; creation / undo of bindings
declarative reading alone may not predict termination or effects
6
early implementation papers describe its working data structures
author found the reproduced diagrams difficult to follow
7
Warren Abstract Machine: introduced in 1983
stack, heap and trail support execution / backtracking
many Prolog implementations compile to related abstract operations
8
Ait-Kaci's 1991 tutorial reconstructs the WAM
author still regards its explanation as demanding
11.4.2 SWI-Prolog
SWI-Prolog supports interactive queries, source loading, scripts, and
application startup. The book's examples expose alternative solutions
and choice points, then discuss version-specific argument handling,
prompts, signals, and executable-building conventions.
Detailed notes - 11.4.2: SWI-Prolog
1
book uses SWI-Prolog; executable normally swipl
interactive prompt: ?-
X is 2 * 2. evaluates arithmetic and reports X = 4
author's claims about alternative implementations describe his assessment at the time of writing
2
member relates a value to a list containing it
member(100,[1,2,3]) fails
successful query may leave alternatives to explore
; requests another answer; . accepts the current answer
3
member(X,[1,2,3]) enumerates X = 1, then 2, then 3
each further answer resumes search at an alternative
4
whether the prompt waits depends on remaining choice points
last-element optimization can establish that no alternative remains
5
halt. or end-of-input leaves the interactive interpreter
6
load source using consult('myprog.pl'). or ['myprog.pl'].
swipl -s myprog.pl loads it before entering the interactive loop
7
SWI-Prolog convention: .pl source suffix
also used by Perl, which the author finds inconvenient
8
author reports suffix-related failures in his tested setup
describes tracing attempted filenames to diagnose them
9
book therefore consistently uses .pl for Prolog examples
10
script starts with #!/usr/bin/swipl
merely loading a file may leave the interpreter interactive
11
book's simple greeting executes write, nl and halt in a directive
-q suppresses startup / informational output
shebang example: #!/usr/bin/swipl -q
12
/usr/bin/env can locate swipl through PATH
author notes the argument-limit tradeoff of traditional shebangs
list excludes the executable name in the script example
14
printing the raw argument list is only a teaching shortcut
user-facing output should follow the application's intended format
15
current_prolog_flag(argv,Argv) also retrieves arguments
custom main/0 must arrange normal termination itself
16
author reports unsolicited input prompts and debugger entry on Ctrl-C
relevant behaviour depends on runtime mode / version
17
book's script sets prompt(_, '') and on_signal(int, _, default)
uses main/0 to avoid a reported SWI-Prolog 6.6.6 interaction
18
standalone-building discussion follows the author's tested setup
options and quirks are historical examples, not universal promises
19
that setup required the expected .pl source suffix
20
book uses custom main/0 and an explicit --goal=main build option
21
compiled argument handling in the author's example differed from scripts
he removed the shebang and used current_prolog_flag
22
build options in the example:
-nodebug, -O: execution / optimization settings
-g true: initialization goal
--goal=main: application's entry goal
--stand_alone=true, -o myprog, -c myprog.pl: saved program output
23
author concludes that these interfaces were unnecessarily awkward
11.4.3 Prolog's data model
Prolog data consists of terms: atomic values, variables, and compound
structures identified by functor and arity. Operator syntax still
constructs terms, lists retain head-tail structure, and variable binding
is distinct from imperative reassignment.
Unification makes two terms agree by binding free variables,
including variables inside partially constructed structures. It does not
enumerate alternative substitutions by itself, and implementations
without an occurs check can construct cyclic terms.
Detailed notes - 11.4.4: Unifying terms
1
unification makes two terms equal by binding their free variables
may succeed with new bindings or fail when incompatible
2
operator = performs unification
[1,X] = [Y,2] -> X = 2, Y = 1
atomic terms must match
bound variables are followed to their values
free variables can bind to matching terms
compound functor / arity must agree; corresponding arguments unify
every argument must match consistently with earlier bindings
3
one unification does not enumerate alternative substitutions
success produces the most general compatible bindings
multiple Prolog answers arise from alternative clauses / searches
4
X = Y can link two initially free variables
later binding either one constrains the other to the same value
5
implementation can make one variable refer to the other
orientation does not change their logical relationship
6
explicitly equating two names is often avoidable in source
replace both with one name when they play the same role
compound-term matching still creates such links implicitly
7
X = f(Y) binds X while Y can remain free
filling Y later refines the structure seen through X
8
unification without an occurs check can create rational / cyclic terms
X = f(X) produces a cycle, not a finite tree
X = [1,2|X] repeats 1,2 indefinitely under traversal
unifying that list with [1,2,1|Y] gives a tail repeating 2,1
11.4.5 Relations, predicates and facts
A relation describes satisfying tuples, while facts list particular
cases and predicates provide executable descriptions. Names and arities
identify predicates, and fact-based relations can also serve as the
program's database.
Detailed notes - 11.4.5: Relations, predicates and facts
1
relation is the central logical model used here
2
binary relation over A and B specifies which pairs (a,b) belong to it
can be written a R b
3
geometrical example: ellipses inscribed in / around triangles
a relation can connect many objects on both sides
need not determine one unique output for each input
4
when A = B, familiar examples include equality, order and divisibility
3 < 7 states that the pair belongs to the less-than relation
5
a relation is a subset of the Cartesian product
R is contained in A x B
completely specified by which pairs belong and which do not
6
n-ary relations contain tuples of n elements
same idea extends to unary and zero-argument cases
7
mathematical relations need not have a computable membership test
their definition alone does not provide an algorithm
8
book treats a predicate as the logical description of a relation
avoid picturing it only as a routine returning a boolean
interest lies in all tuples satisfying it
9
predicate / relation terminology comes from different mathematical areas
book emphasizes the common underlying set of satisfying tuples
10
relational-database tables also model sets of tuples
stored table is finite
Prolog procedure may generate indefinitely many solutions
11
unary relation selects individual elements
zero-argument relation concerns the single empty tuple
either contains that tuple, or does not
12
true succeeds; fail / false fail
repeat succeeds and can succeed again on every backtracking visit
repeated proof paths are an operational property, beyond a set's simple membership interpretation
13
user equivalents: success. and failure :- 1 = 2.
always-failing defined procedure differs from an undefined name
undefined procedure normally causes an error
14
repeated success can use a fact followed by a recursive clause
forever. then forever :- forever.
other zero-argument procedures can have effects, including cut
15
predicate identity: atom name plus arity
same compound notation can denote a goal or ordinary data
16
variables do not declare a fixed data type
relation arguments range over the relevant Prolog term universe
17
procedure emphasizes executable behaviour
book uses procedure or predicate according to context
Rules connect a matching head to goals that must succeed. Prolog
tries clauses in order and backtracks to available choice points,
undoing bindings and exploring alternatives when a later goal fails.
Detailed notes - 11.4.6: Rules and procedures
1
rules describe cases without explicitly listing every satisfying tuple
loves(X,Y) :- parent(X,Z), parent(Y,Z) would infer affection from a shared child; author rejects it as a real-world assumption
loves("Don Juan",X) :- female(X) expresses the example's rule
loves("Vorona",_) accepts any second argument
each bare _ is a fresh anonymous variable
one-occurrence named variables can produce singleton warnings
book calls variable-containing unconditional clauses rules; ordinary Prolog terminology also permits non-ground facts
2
program consists of clauses, each ending with a dot
rule: Head :- Body.
body absent: unconditional clause
head absent: directive executed when the source is processed
3
head identifies the procedure by its functor / arity
clauses normally grouped together for readability
their source order determines the order of attempted alternatives
4
body combines goals
comma: conjunction, both must succeed
semicolon: disjunction, an alternative may succeed
parentheses override grouping; comma binds more tightly
5
goal is a term used as a procedure invocation
conjuncts normally execute left to right
6
goal may fail, succeed once or succeed with remaining alternatives
choice point stores where another attempt can resume
disjunction also introduces alternatives
7
backtracking returns to the latest available choice point
undoes bindings made along the abandoned search path
8
built-in procedures can implement special operations / effects
user-defined procedures follow the ordinary clause-search rules
9
procedure invocation tries clause heads in order
unify goal with a fresh instance of a head
successful unification -> solve that clause's body
retain a choice point if further clause alternatives remain
10
last matching clause needs no choice point for later clauses
goals inside its body may still create their own alternatives
11
failed head unification proceeds to the next candidate clause
exhausting candidates makes the goal fail
12
recursion expresses repeated relational structure
every activation has fresh local variables
matching can link variables across these separate instances
Book example (1 file) - 11.4.6: Rules and procedures
11.4.7 Procedure calls, argument modes and
inversion
Different argument modes let one relation check values, find missing
values, or enumerate structures, as ancestry and list joining
illustrate. Logical reversibility does not guarantee termination or
useful enumeration in every mode.
Detailed notes - 11.4.7: Procedure calls, argument modes and inversion
1
goal arguments can be constants, variables or partially built structures
bound variables behave as their values
solving a goal may bind initially free variables
2
logical reading: find values satisfying the relation
procedural reading: free arguments can receive outputs
3
ancestor example adds recursion to parent facts
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
direct parent, or parent of an ancestor of Y
4
book adjusts older SWI double-quote interpretation for string names
other dialects may require atoms or different text conventions
5
ground queries check a relationship
Lucas is Laura's ancestor; Jason is Joseph's
Jason is not Fred's ancestor in the supplied tree
6
several ancestry paths can produce repeated successful proofs
even a ground query can therefore leave alternatives
7
leaving arguments free asks for related people
ancestor(X,"John") finds Jessica, Lucas, Jason in search order
ancestor("Jason",X) finds his descendants
ancestor(X,Y) enumerates all 22 pairs in the supplied example
8
argument modes describe which arguments are supplied / free
(+,+), (+,-), (-,+), (-,-)
one relation working in different directions -> inversion
9
this flexibility supports declarative thinking
describe the required relationship instead of a fixed input-output direction for every procedure
10
del_any removes zero or more occurrences of a selected element
n matching occurrences give 2^n keep/delete choices
distinct choices can sometimes produce the same resulting list
11
del_any(Element,Source,Result) is a ternary relation
Result is obtainable by optional deletion of Element from Source
12
three recursive cases:
del_any(_,[],[]).
matching head: delete it and recurse on the tail
any head: retain it and recurse, attaching it to the result tail
Cut commits part of the current search, while negation as failure
tests whether a goal currently has a proof. Both depend on execution
order and bindings, and careless pruning can discard valid solutions
instead of merely avoiding barren search.
Detailed notes - 11.4.8: Negation and cut
1
cut, written !, commits within the current procedure invocation
discards its alternative clauses and choices created to the left since that invocation began
later failure does not restore those alternatives
2
cut affects procedural search, not just logical relationships
can improve termination / efficiency or remove valid answers
therefore can restrict supported argument modes
3
negation as failure: not(T), commonly written \+ T
succeeds if attempting T fails
fails if T finds a solution
exports no bindings made while testing T
4
this is not a generator of values satisfying logical negation
5
order-sensitive example:
X = abra, Y = kadabra, not(X = Y) succeeds
X = abra, not(X = Y), Y = kadabra fails
second version tests while Y is free, so X = Y can succeed
6
A \= B tests that A and B cannot unify now
equivalent to negation-as-failure of A = B
does not install a persistent inequality constraint
7
book uses not; SWI documentation normally uses \+
8
del_all must delete every matching occurrence
keeping both unrestricted delete / keep clauses would still define the nondeterministic del_any relation
9
guard the keep clause with X \= Element
works when source and deletion element are supplied
del_all(X,[1,2],[2]) finds X = 1
del_all(X,[1,2],[1]) fails although supplied X = 2 succeeds
free Element makes the early non-unification test fail
10
var / nonvar could dispatch to separately implemented modes
inversion would then require extra procedural code
11
cut version commits when empty-list or matching-head case applies
base clause ends with !
delete clause starts its body with !, then recurses
remaining keep clause no longer needs the negative guard
removes useless alternatives in the intended supplied-input mode
12
return to accumulator-based listrev
smallest problematic reverse query: listrev(X,[])
13
trace must distinguish same-named variables in different activations
book uses depth indices for that explanation
14
variables / structures can survive an individual predicate activation
runtime must preserve bindings still reachable by the computation
15
printed fresh variables can have generated names
pred(X,Y) :- X = f(Y) queried with pred(X,_) can print X = f(_G894), with an implementation-generated suffix
16
listrev/2 forwards the query to listrev(X,[],[])
initial accumulator and required result are both empty
17
base clause succeeds with X = []
recursive clause remains an alternative
18
after that answer, backtracking undoes X's binding
recursive alternative sets X to [H|T]
calls helper with required result [] but accumulator [H]
19
base case can no longer match the nonempty accumulator to []
cut after successful helper base case stops that later search
listrev([],A,A) :- !.
intended forward / reverse finite-list modes now finish
21
cut can therefore improve usable inversion in a particular mode
does not imply every use of cut preserves all modes
22
in del_all_cut, pruning changes which solutions the clauses admit
removes keep choices for matching elements
23
in the finite-list listrev modes discussed, pruning removes a barren search branch without changing the required answer
this operational distinction motivates the usual green / red cut distinction; correctness depends on the intended modes
11.4.9 Arithmetic
Arithmetic-looking terms are not evaluated until an operation such as
is demands their numeric result. Ordinary arithmetic requires suitable
bound inputs rather than solving equations, and bounded generators must
stop search without prematurely cutting off answers.
Detailed notes - 11.4.9: Arithmetic
1
arithmetic includes integers, floating-point and rational values
-1 * (3 * X - 25) does not evaluate merely by being written
can be stored, matched or embedded in another term
3
is evaluates its right argument and unifies the result with its left
X is 4*5 -> X = 20
then A is -1*(3*X-25) -> A = -35
every variable used arithmetically must already have a value
an unbound arithmetic operand causes an error, not ordinary failure
4
list-length example first obtains the tail length, then adds 1
listlen([],0)
recursive clause: listlen(T,TL), L is TL+1
<, >, =<, >=, =:=, =\= evaluate both operands before comparison
numeric equality =:= differs from term unification =
5
ordinary is / comparison operations are evaluators, not equation solvers
this limitation does not describe separate constraint libraries
arbitrary expressions do not admit a universal symbolic solver
6
prefix(Prefix,List,N) can compute using known N
base: prefix([],_,0)
recursive case decrements N, then processes matching list heads
supplying two lists but leaving N free fails at N2 is N-1
7
later section uses binding-state tests to support different modes
8
ten/1 example seeks the integers 1 through 10 without listing them
direct facts or member with a fixed list would work but do not illustrate the search problem being investigated
9
naive recursion: ten(1); then ten(Y), X is Y+1, X =< 10
finds all ten answers for free X
afterward keeps recursively searching without termination
unsuitable supplied values can also cause endless search
10
moving the bound test is insufficient
before recursion: free argument is not yet evaluable
after recursion: search can still remain unbounded
11
unconditional cut at the wrong point also fails
before recursion does not remove recursive search choices
after first recursive answer can discard later valid answers
12
trace explains lost answers
recursive Y = 1 yields X = 2
cutting its remaining alternatives prevents generation of 3,4,...
behaviour also changes between supplied and free X
13
commit only when the generation boundary has been reached
smaller Y must retain alternatives
14
working version:
ten(1).
ten(X) :- ten(Y), ((Y >= 10, !, fail); X is Y+1).
at boundary: cut and fail
below boundary: compute next value without pruning later answers
15
alternative bounded generator mbetween(A,B,X):
A > B -> cut and fail
otherwise offer X = A
subsequent alternative increments A and recurses
ten(N) becomes mbetween(1,10,N)
supplied bounds make progress / termination explicit
11.4.10 Input and output
Explicit stream objects separate independent I/O uses more reliably
than changing a shared current filename. Prolog distinguishes
characters, codes, and bytes, and I/O exceptions need handling
separately from ordinary goal failure.
Detailed notes - 11.4.10: Input and output
1
author recalls his criticisms of older Lisp / Scheme I/O conventions
2
book distinguishes Edinburgh-style and ISO-style Prolog I/O
mainly differ in how files / current streams are managed
3
write prints values; nl adds a newline
read parses Prolog syntax, which needs care as a user-input format
author recommends explicit character processing for these examples
4
old get skips whitespace; get0 reads it too
binds output argument to the character code
-1 indicates EOF in the examples
5
put outputs a character given its code
put(65) prints A under the illustrated character encoding
6
text input decodes characters according to stream encoding
non-ASCII character code can differ from its original input bytes
7
byte input requires suitable stream configuration
get_byte is intended for byte-oriented streams
book uses encoding(octet) to obtain unconverted byte values
8
get_code obtains a code; get_char obtains a one-character atom
get_char reports EOF using end_of_file
9
corresponding outputs: put_code, put_char and put_byte
character and byte interfaces must match the chosen stream model
10
Edinburgh style keeps a current input stream
see(File) opens / selects it
seen closes current file and restores standard input
see(user) switches to user input without closing another file
11
copy-file example uses repeat and backtracking as a loop
read a character
EOF -> succeed, cut off repeat, close file
otherwise print character and fail deliberately
-> backtrack to repeat and read the next character
12
tell / told similarly select / close current output
append opens for appending
seeing / telling retrieve current stream designators
save current output, append a greeting to a file, restore output
13
using filenames as stream identities makes independent uses interfere
a module may unknowingly select a file already in use elsewhere
14
SWI exceptions can handle failures in the older I/O interface too
15
newer interface exposes distinct stream objects
optional atom aliases identify streams separately from filenames
printed stream representation is not ordinary readable source data
16
user_input / user_output / user_error initially denote standard streams
Binding-state tests can select implementations for different argument
modes; nonvar does not imply every nested variable is bound. Term
decomposition and text-conversion relations expose structure without
confusing atom names, string values, and character codes.
Detailed notes - 11.4.11: Analysing atoms and terms
1
built-ins expose information about terms and bindings
2
var(X) succeeds when X is currently a free variable
linking two free variables still leaves var true for both
var(f(X)) fails even when X is free: f(X) is already a compound
3
nonvar succeeds for every non-variable term
does not require a compound term's internal variables to be bound
4
binding-state tests are procedural facilities
can dispatch between implementations for different argument modes
5
prefix example selects arithmetic order according to N
nonvar(N): decrement N before recursing
var(N): recurse first, then calculate N from the tail length
prefix(P,[1,2,3],N) enumerates lengths 0,1,2,3 and their prefixes
=.. relates a term to [Functor|Arguments]
-> X =.. [a,b,c] constructs a(b,c)
-> p(1,2,3) =.. Y gives [p,1,2,3]
construction / decomposition require enough structure on one side
6
name/2 relates atom or number to character-code list
name(12321,X) -> [49,50,51,50,49]
name(X,[55,55,55]) -> 777
string_codes relates a string object to codes
atom_string relates an atom to a string object
11.4.12 Lists of solutions
findall collects a template instance for every successful proof and
returns an empty list when none exist. bagof groups by omitted free
variables, while setof additionally sorts and deduplicates; complete
collection requires the search to finish.
Detailed notes - 11.4.12: Lists of solutions
1
findall(Template,Goal,List) collects every answer from Goal
requires search to finish before producing its complete list
no answers -> []
2
template determines what is copied into the list for each success
can contain one variable, several variables or a constructed term
3
color facts red / green / blue illustrate template choices
X -> [red,green,blue]
[X] -> [[red],[green],[blue]]
f(X) -> [f(red),f(green),f(blue)]
X+X builds terms such as red+red; no arithmetic is implied
constant template yields repeated copies of that constant
ancestor example uses [A,D] or A/D to retain both related people while excluding direct-parent pairs
4
interactive answer printing can abbreviate long lists
explicit write(L), nl displays the collected structure
book then uses abort to stop further query-result presentation
5
bagof groups by free goal variables omitted from the template
bagof(D,(ancestor(A,D),not(parent(A,D))),L)
separate descendant list for each A
multiple groups appear as separate backtracking answers
unlike findall, bagof fails when there are no solutions
6
setof also sorts each answer list and removes duplicates
otherwise uses bagof-style grouping
11.4.13 Working with the database
Dynamic predicates allow facts and rules to change during execution
through assertion and retraction. This can represent mutable data, but
also changes executable behavior, making the distinction between parsing
data and loading code important.
Detailed notes - 11.4.13: Working with the database
1
dynamic predicates can change during execution
:- dynamic parent/2, male/1, female/1.
asserta inserts a clause before existing clauses
assertz inserts after them
position affects search order; SWI's assert follows assertz
2
retractall removes every clause matching the supplied head pattern
retractall(parent("Jessica",_)) removes her parent entries
succeeds even when nothing matched
3
retract removes matching clauses one at a time
binds variables to the removed clause's values
on backtracking, can remove further matching clauses
fails when matching possibilities are exhausted
assertion / retractall can establish a previously absent dynamic predicate in SWI; explicit declaration still communicates intent
4
dynamic rules can change executable behaviour as well as data
author warns against constructing executable clauses from unchecked external input
5
author recommends keeping data parsing separate from loading code
consult executes source; read alone parses terms, so how parsed terms are subsequently used also matters
6
database can imitate global mutable variables
global_vars(Name,Value) stores one binding per chosen name
assign_var retracts old entries, then asserts the new one
updates are effects and are not undone by ordinary backtracking
author discourages this as a substitute for relational programming
11.4.14 Formatting Prolog code
Formatting should expose clause boundaries, conjunctions, and
alternative branches. Fixed indentation avoids making body depth depend
on head length, while visible disjunction separators and grouping make
the search structure easier to follow.
Detailed notes - 11.4.14: Formatting Prolog code
1
clause-based languages group similar heads into procedures / functions
formatting should make both clause boundaries and body structure easy to see
2
short clause may fit on one line
otherwise put body below the head with a fixed indentation
choose consistently between compact body lines and one goal per line
avoid aligning later goals under a first goal after a long head
-> would make indentation depend on head length
3
disjunction requires visible separation of alternatives
short alternatives can occupy separate lines
long alternatives can use condition / cut as a branch header
separate semicolons make alternative boundaries clear
align grouping parentheses and use a constant indentation step for nested goals
11.5 Lazy evaluation
Lazy evaluation delays computation until a result is demanded,
enabling finite use of potentially infinite structures. Hope examples
develop this model through typed functions, folds, recursive bindings,
and character streams for interaction.
11.5.1 Two possible strategies for evaluating
expressions
Lazy evaluation retains suspended computations and shares their
results when demanded. Unused arguments may never run, changing
termination as well as cost; unrestricted side effects therefore cannot
depend on ordinary textual evaluation order.
Detailed notes - 11.5.1: Two possible strategies for evaluating
expressions
1
eager evaluation computes an expression when its value is needed for a binding, such as an ordinary function argument
arguments are evaluated before the function body uses them
also commonly called strict evaluation
2
a higher-level value need not have only one machine representation
it can be represented by an expression that will produce the value
static typing does not prevent such a representation
3
lazy evaluation delays work until the value is actually demanded
retain the expression in an unevaluated form
evaluate it when necessary and share the resulting value
4
unused function arguments need never be evaluated
f uses y only when x is zero
f(1, g(a,b)): return from the x branch without evaluating g
eager argument evaluation would compute g before entering f
5
this can also change termination
if the unused g diverges, eager evaluation never reaches f's result
lazy evaluation can still produce it
6
laziness is not a universal speed optimization
delayed computations need storage and bookkeeping
eager code can also avoid known unnecessary work
the main interest is its programming model
7
lazy structures can be potentially infinite
keep the unrequested remainder as a suspended computation
compute another finite part whenever it is demanded
no finite request requires materializing the entire structure
8
uncontrolled side effects conflict with demand-driven evaluation
an expression may run later than expected or never run
output / mutation cannot rely on textual evaluation order alone
pure lazy languages need explicit mechanisms for ordered effects
The chapter uses Hope and the Hopeless implementation to isolate lazy
evaluation and static typing in a small teaching language. Comparisons
with Haskell, Miranda, and Clean reflect the author's instructional
choice and historical context.
Detailed notes - 11.5.2: Hope and other lazy languages
1
pure functions readily transform available inputs into results
interaction is harder: later input can depend on earlier output
lazy languages need a model for ordering that interaction
Haskell is the prominent example discussed by the book
2
the author finds Haskell too involved for this short introduction
wants the evaluation model visible without extensive extra machinery
this is a teaching choice and assessment, not a language limitation
3
Hope is chosen as a small illustrative language
historically used in Field and Harrison's functional-programming book
demonstrates lazy evaluation and static typing with type inference
the implementation discussed here is Hopeless
4
Miranda and Clean are mentioned as other lazy languages
the historical licensing / availability remarks reflect the book's date
Hope keeps the examples small enough for this chapter
11.5.3 The Hopeless interpreter
Hopeless supports interactive evaluation, file execution, modules,
editing, and saved session definitions. Its declarations and defining
equations introduce the teaching language, while the interpreter's
experimental status limits expectations for application deployment.
Detailed notes - 11.5.3: The Hopeless interpreter
1
the implementation began with Ross Paterson
the book recounts later maintenance and disappearing project sites
2
the author distributes a modified version
includes reading standard input through an empty filename
build the downloaded source as an ordinary user
installation places binary, manual and library files under /usr/local
3
the archive version named in the book is historical
its exact filename is not a language requirement
4
-f tells Hopeless to read program text from a file
usable in a script shebang
write argv prints the command-line arguments
without -f, use the interactive interpreter
rlwrap supplies command editing / history
5
interactive prompt: >:
ordinary Hope sentences end with a semicolon
a newline alone may leave the interpreter waiting for more input
6
edit is an exception to the semicolon requirement
supplying one remains acceptable
7
enter an expression to evaluate it
output includes both value and type
2 + 3 -> 5 : num
dec declares a named value's type; --- supplies its definition
cube : num -> num
cube x is defined as x*x*x
8
use module loads a module
the described interpreter appends .hop and searches locally
file-loading flexibility is limited in this implementation
9
edit module invokes the editor from EDITOR, or vi by default
after editing a loaded module, its definitions are refreshed
10
editing errors cause the interpreter to reopen the editor
diagnostic lines begin with @
correct the error or comment out unfinished code with !
11
use can also enter this editing cycle when a loaded file contains errors
12
display shows definitions entered during the current session
loaded modules appear as use directives rather than expanded contents
save writes this session state to a .hop file
13
Hopeless is an experimental teaching implementation
its I/O limitations become apparent later
11.5.4 Hope's lexical rules and syntax
Hope programs use semicolon-terminated sentences, ordinary and
symbolic identifiers, and configurable infix notation. Many arithmetic
operators are library function names rather than reserved syntax,
separating expression notation from the language's declaration
forms.
Detailed notes - 11.5.4: Hope's lexical rules and syntax
1
program consists of semicolon-terminated sentences / directives
a sentence may span several lines
line width is a readability convention, not an interpreter limit
2
lexical elements:
! begins a comment through the end of the line
commas, semicolons, parentheses and brackets are delimiters
number, character and string literals use familiar notation
quoted characters / strings allow escapes such as \n and \t
identifier forms:
letters / underscores followed by letters, digits or underscores
trailing apostrophes are allowed
symbolic names made from suitable punctuation characters
word-like and symbolic tokens can be adjacent, as in a+b-25
3
reserved syntax includes declaration, type and expression keywords
dec, data, type, lambda, let, letrec, if, then, else
also directive names and punctuation such as --- and <=
some reserved words exist for compatibility with other dialects
backslash, use and infixrl alias lambda, uses and infixr
4
infix / infixr can declare operator-like use of nonreserved names
allow custom infix expression notation
5
arithmetic and comparison operators are library function names
+, -, *, /, div, mod, =, /=, <, =<, >, >=
their names are not reserved syntax
no unary minus: write 0 - z when needed
6
built-in type names and many predefined names are not keywords either
11.5.5 Data model and type system
Hope combines static typing with tuples, homogeneous lists,
constructor-based alternatives, and parameterized recursive types. Type
aliases name existing forms, while data declarations introduce new
constructors; strings are lists of characters.
Detailed notes - 11.5.5: Data model and type system
1
Hope is statically typed
functions accept / return values of appropriate types
list elements must share one type
compound types are built from simpler ones
2
three basic types in this implementation:
num: numeric values represented using C double
truval: true / false
char: single-byte characters
3
the historical dialect in the referenced textbook differs
num represents integers there, with a separate real type
4
tuple: fixed number of ordered components, possibly of different types
functions accept and return values that may themselves be tuples
a multiargument function can be viewed as taking one tuple
5
list: variable-length sequence of elements of one type
length is not part of its type
6
constructors distinguish structured alternatives
resemble Prolog functors, but belong to declared types
a nullary constructor is a distinct named value
++ separates alternatives, such as red ++ green ++ blue
7
data introduces a new type and its constructors
data Rainbow == red ++ orange ++ ...
data PlanePoint == Point(num # num)
type names and constructor names are separate declarations
++ and new constructors occur at the declaration's outer level
unlike #, which can form a tuple type wherever a type is expected
8
MaybeNum example: Good(num) ++ Bad
SafeDiv(_,0) returns Bad
otherwise return Good(x/y)
failure is represented explicitly in the result type
constructor identity also includes arity in this implementation
Point with two and three components can belong to different types
same constructor name / arity cannot be reused in another type
9
type defines an alias; data introduces a constructor-based type
type Vec3num == num # num # num
a plain tuple needs no new data constructor
10
recursive data declarations can describe lists
NumList: NumNil or NumCons(number, another NumList)
separate fixed-element types would otherwise need new constructors
parameterized type avoids that repetition:
List(any): Nil or Cons(any, List(any))
List(num), List(char), List(List(char)) belong to one family
constructors are shared across that family
11
a one-element tuple is just the element
parentheses can be omitted around a simple argument
commas create tuple structure; parentheses mainly group expressions
12
type application also permits omission of unnecessary parentheses
List any and List(any) express the same parameterized type
13
Nil has a polymorphic element type
its value contains no element that would constrain that type
the interpreter reports an unknown type variable, such as alpha
14
built-in lists already provide this construction
type constructor: list
empty list: nil or []
head :: tail constructs a nonempty list
:: associates to the right
1 :: 2 :: 3 :: nil equals [1,2,3]
15
string is a list of characters
"Hope" equals ['H','o','p','e']
11.5.6 Functions in Hope
Function declarations give types and defining equations use patterns
to select cases. Hopeless chooses a most-specific matching pattern
rather than Prolog's clause order, so overlapping patterns should not
rely on unspecified tie-breaking behavior.
Detailed notes - 11.5.6: Functions in Hope
1
declare a function using dec
define it with one or more --- equations
2
these directives can also introduce constants
dec gives a name and its type after :
--- gives the defining value after <=
3
function type: argumentType -> resultType
Cube: num -> num; result x*x*x
SumProd: num # num -> num # num
SumProd(5,6) returns (11,30)
4
several defining equations use pattern matching
DropElems example, for an intended nonnegative count:
empty input list -> empty list
zero count -> original list
otherwise remove the head and recurse with count minus one
_ marks an unused pattern component
avoids inventing names for ignored values
the implementation selects a most-specific matching pattern
clause order is not the Prolog-style selection rule
5
most-specific selection can still leave ambiguity
DropElems(0,[]) matches both base cases
this example is harmless because both return []
6
deep constructor patterns can make matching more complicated
overlapping cases can imply different results
the implementation promises deterministic but otherwise unspecified selection in such cases
avoid depending on an unspecified tie-breaking choice
dec Nth : list(alpha) # num -> alpha;
--- Nth(x::ls, n) <= if n = 1 then x else Nth(ls, n-1);
dec FirstN : list(alpha) # num -> list(alpha);
--- FirstN(x::y, n) <= if n = 0 then nil else x::FirstN(y, n-1);
dec map : (alpha -> beta) # list(alpha) -> list(beta);
--- map(_, []) <= [];
--- map(f, x::ls) <= f(x) :: map(f, ls);
dec Reduce : (alpha # beta -> beta) # list(alpha) # beta -> beta;
--- Reduce(_, [], init) <= init;
--- Reduce(f, h :: t, init) <= f(h, Reduce(f, t, init));
dec Member : alpha # list(alpha) -> truval;
--- Member(x, ls) <=
Reduce(\(el, ok) => if ok then true else x = el,
ls, false);
dec MakeAdder : num -> num -> num;
--- MakeAdder x <= lambda y => x + y;
dec DropElems : num # list(alpha) -> list(alpha);
--- DropElems(_, []) <= [];
--- DropElems(0, ls) <= ls;
--- DropElems(k, _ :: tail) <= DropElems(k-1, tail);
dec MakeSeq : num # num # num -> list(num);
--- MakeSeq(x, y, d) <= if x > y then [] else x :: MakeSeq(x+d, y, d);
dec Twist : list(alpha) # list(alpha) -> list(alpha);
--- Twist(_, []) <= [];
--- Twist([], _) <= [];
--- Twist(x :: t1, y :: t2) <= x :: y :: Twist(t1, t2);
dec DropElC : num -> list(alpha) -> list(alpha);
--- DropElC 0 <= \ x => x;
--- DropElC k <= \ [] => [] | (_ :: tail) => DropElC (k-1) tail;
dec DropElCC : num -> list(alpha) -> list(alpha);
--- DropElCC k <=
if k = 0
then \ x => x
else \ [] => [] |
(_ :: tail) => (DropElC (k-1)) tail;
dec Curry : (alpha # beta -> gamma) -> alpha -> beta -> gamma;
--- Curry f <= \x => \y => f(x, y);
11.5.7 The if and let expressions
if produces a value from one selected branch, and let binds or
unpacks a local result through a pattern. The word-splitting example
combines these forms to organize a recursive transformation of character
lists.
Detailed notes - 11.5.7: The if and let expressions
1
function bodies can combine arithmetic, constructors and function calls
if adds conditional values
let / where add local names
the chapter develops if and let
2
if A then B else C is an expression
A must be boolean
B and C must have the same type
evaluate only the selected branch to obtain the result
both branches are required; there are no effect-only statements here
3
let V == E in B introduces local bindings through a pattern
match pattern V against E; use its bound names in B
shared binding avoids writing the same computation repeatedly
let x == f(a,b,c) in (p(x),q(x),r(x))
patterns can unpack structured results:
tuple (x,y,z): extract three components of a returned vector
list [x,y,z]: extract three list elements
head :: tail: separate a nonempty list
compute sqrt(x*x+y*y+z*z) from the extracted coordinates
4
patterns can use previously declared constructors
a variable may occur only once in the pattern
new local variables are not in scope within E
let matching is therefore not Prolog unification
5
a same-named variable inside E refers to an enclosing binding
otherwise it is an unbound-name error
recursive bindings require letrec in this implementation
6
BreakString: split a character list into a list of word strings recursive helper works on the tail before the current character
returned list's first word is considered unfinished
nonspace: prepend the current character to that first word
space before a nonempty word: prepend a new empty unfinished word
space before an empty unfinished word: ignore the extra space
7
base case: empty input returns [[]]
one empty unfinished word preserves the helper's invariant
8
wrapper removes a remaining leading empty word
needed for empty input, all-space input and leading spaces
the worker is named BreakStringDo
9
let unpacks the worker result; if tests whether the first word is empty
nonspace branch rebuilds (c :: Word) :: List
space branch either preserves the empty word or starts a new one
alternative without if / let:
DropFirstEmpty uses patterns to remove an initial empty word
CharToFirstWord prepends a character to the first word
helper calls and pattern equations express the same algorithm
Book example (1 file) - 11.5.7: The if and let expressions
! dec BreakStringDo : list(char) -> list(list(char));
! --- BreakStringDo([]) <= [[]];
! --- BreakStringDo(' ' :: Rest) <=
! let Word :: List == BreakStringDo(Rest) in
! if Word = [] then [] :: List else [] :: Word :: List;
! --- BreakStringDo(c :: Rest) <=
! let Word :: List == BreakStringDo(Rest) in (c :: Word) :: List;
!
! dec BreakString : list(char) -> list(list(char));
! --- BreakString(str) <=
! let Word :: Rest == BreakStringDo(str) in
! if Word = [] then Rest else Word :: Rest;
dec DropFirstEmpty : list(list(char)) -> list(list(char));
--- DropFirstEmpty([] :: T) <= T;
--- DropFirstEmpty(H :: T) <= H :: T;
dec CharToFirstWord : char # list(list(char)) -> list(list(char));
--- CharToFirstWord(c, W :: L) <= (c :: W) :: L;
dec BreakStringDo : list(char) -> list(list(char));
--- BreakStringDo([]) <= [[]];
--- BreakStringDo(' ' :: Rest) <=
[] :: DropFirstEmpty(BreakStringDo(Rest));
--- BreakStringDo(c :: Rest) <=
CharToFirstWord(c, BreakStringDo(Rest));
dec BreakString : list(char) -> list(list(char));
--- BreakString(str) <=
DropFirstEmpty(BreakStringDo(str));
11.5.8 Polymorphic functions
Type variables let one function handle lists of different element
types without changing its defining equations. Static polymorphism
removes duplicate algorithms, while type inference determines local
details and implementation specialization remains separate from source
meaning.
Detailed notes - 11.5.8: Polymorphic functions
1
DropElems never examines the type of a list element
its algorithm works for characters, numbers or other values
only its original numeric declaration was too restrictive
2
this resembles the motivation for C++ function templates
static typing need not force duplicate algorithms
3
polymorphic declarations use type variables
alpha, beta and gamma are predefined
typevar introduces more names when needed
general DropElems type:
num # list(alpha) -> list(alpha)
keep the existing equations unchanged
local variable types are inferred rather than written in the body
4
data declaration parameters need no separate typevar declaration
their role is clear from that context
dec must distinguish type variables from concrete type names
5
Hopeless does not expose C++'s template / generated-instance distinction
no separate compilation and linking boundary is involved here
callers use the polymorphic function directly
6
internal specialization is an implementation question
changing such internal choices need not change program semantics
11.5.9 Anonymous functions and higher-order
functions
Higher-order functions accept or return functions, and lambdas create
closures over surrounding bindings. A polymorphic map transforms element
types, while operator sections conveniently fix one operand to create a
one-argument function.
Detailed notes - 11.5.9: Anonymous functions and higher-order functions
1
higher-order functions receive functions as arguments
anonymous functions supply convenient local behavior
closures retain free-variable bindings
immutable bindings simplify the closure model
2
map example: transform every list element and return the result list
3
the example accepts one list and a one-argument function
unlike variadic map facilities in some Lisp dialects
4
input elements have type alpha; transformation results have type beta
the supplied function therefore has type alpha -> beta
a let binding can name it, or it can be applied immediately
6
-> associates to the right
num -> num -> num means num -> (num -> num)
operator sections fix one operand:
(+t): x -> x+t; (t+): x -> t+x
(-2) subtracts 2; (20-) subtracts its argument from 20
mapping (::[100]) creates [value,100] for each input element
7
an infix operator in parentheses denotes its two-argument function
(+) corresponds to lambda (x,y) => x+y
8
anonymous functions can contain several pattern clauses
separate alternatives with |
example: remove an initial empty list when present
Hopeless infers the lambda expression's type
9
ordinary let can be expressed by function application
let P == E in B equals (lambda P => B) E
11.5.10 The letrec expression
letrec makes new names available within their own definitions,
supporting local recursion and mutual recursion. Under lazy evaluation
it can also define cyclic data, such as an alternating infinite list,
without destructive updates.
Detailed notes - 11.5.10: The letrec expression
1
letrec V == E in B resembles let
its new names are available in both E and B
permits a definition to refer to itself
2
local recursive / mutually recursive functions are an immediate use
bind a local drop_elems lambda
its recursive branch can refer to drop_elems
no global declaration is required
3
laziness also permits recursive data
letrec lst == 1 :: 2 :: lst
lst begins with 1 and 2, then continues with itself
taking five elements gives [1,2,1,2,1]
:: is right-associative: 1 :: (2 :: lst)
4
an eager Lisp / Scheme list can instead be made cyclic by mutation
replace its final tail with a reference to the list itself
Hope constructs the cycle through a recursive lazy binding
the example requires no destructive update
11.5.11 Folding lists
A lazy right fold need not demand its recursive tail result. A
membership combiner that tests the current element first can stop
immediately, whereas testing the folded tail first forces unnecessary
traversal and can prevent termination.
Detailed notes - 11.5.11: Folding lists
1
fold combines a sequence using a supplied operation
laziness gives this familiar technique additional possibilities
2
the section uses a right fold
unlike a usual accumulator-style left fold, its recursive call is inside the combining operation
demand determines whether that recursive result must be computed
3
right-fold structure:
f accepts an element of alpha and a result of beta
first Member implementation uses the fold to test membership
combiner: if ok then true else x = element
ok is the recursive fold of the remaining list
testing ok first forces traversal of the tail
even Member(1,[1,2,3]) reaches the end before succeeding
if is strict in its condition: choosing a branch needs that value
6
revised combiner: if x = element then true else ok
compare the current element before demanding the recursive result
matching the head returns true immediately
the unevaluated fold of the tail is discarded
a right fold can consequently stop after a finite prefix
7
understanding demand is essential to writing lazy programs
tracing evaluation exposes why equivalent finite results can have very different termination / resource behavior
experience makes these demand relationships easier to recognize
11.5.12 Infinite data structures: examples
Lazy lists represent unbounded sequences while finite consumers
request only the needed portion. Ascending numbers, filtered primes, and
successive rows of Pascal's triangle show how producers can avoid
choosing a complete bound in advance.
Detailed notes - 11.5.12: Infinite data structures: examples
1
lazy data can represent structures whose full evaluation never finishes
even some otherwise eager languages support lazy structures
2
:: is non-strict in both components
From x = x :: From(x+1): an unbounded ascending list
From 1 represents the natural-number sequence
asking for the entire printed result never completes
3
finite consumers make such lists useful
Nth uses one-based indexing in the first example
FirstN returns a prefix of the requested length
Nth(From(20),30) -> 49
FirstN(From(10),3) -> [10,11,12]
these examples assume suitable counts and sufficiently long lists
4
only demanded structure is materialized
the rest remains an unevaluated recursive expression
finding a later element forces enough list structure to reach it
5
prime-number example starts from the idea of sieving
choose the first remaining number as prime
eliminate its multiples from the remaining candidates
a finite initial array requires a chosen upper bound
6
lazy filtering avoids choosing that bound beforehand
Filter(n,list) skips elements divisible by n
Sieve(n::rest) returns n :: Sieve(Filter(n,rest))
apply Sieve to From 2, then take the requested prefix
the 1,000th prime is 7,919; the 10,000th is 104,729
this repeated-filter implementation becomes expensive as work grows
it illustrates laziness rather than an optimized sieve algorithm
7
Pascal's triangle can be an unbounded list of finite rows
NextLineRest:
sum adjacent entries and recurse
final singleton supplies the trailing boundary value
NextLine prepends 1 to complete the next row
PascalsTriangleBuild:
return current row followed by construction from NextLine(current)
start from [1]
Cnk uses zero-based indexing in this second example
select row n, then entry k
only the portion needed for that coefficient is demanded
dec Nth : list alpha # num -> alpha;
--- Nth (x :: ls, n) <= if n = 1 then x else Nth (ls, n - 1);
dec FirstN : list alpha # num -> list alpha;
--- FirstN (x :: y, n) <= if n = 0 then nil else x :: FirstN (y, n - 1);
dec From : num -> list num;
--- From x <= x :: From (x + 1);
dec Filter : num # list num -> list num;
--- Filter (n, m :: ls) <=
if m mod n = 0
then Filter (n, ls)
else m :: Filter (n, ls);
dec Sieve : list num -> list num;
--- Sieve (n :: ls) <= n :: Sieve (Filter (n, ls));
11.5.13 Input and output in Hope
Hopeless represents input as lazy character lists and emits demanded
output through a final write directive. This supports incremental
interaction, but the experimental interface has limited error handling
and coordination of several output destinations.
Detailed notes - 11.5.13: Input and output in Hope
1
Hopeless is experimental and lacks robust application error handling
examples concentrate on the evaluation model
2
ordinary modifying I/O operations do not fit pure expression evaluation
streams need another representation
3
lazy lists provide that representation
an input stream becomes a not-yet-completed list of characters
4
read filename returns a lazy character list
actual reading occurs as characters are demanded
evaluation may block waiting for input
empty filename, "" or [], selects standard input in this version
5
several input streams can coexist as separate lazy lists
combine their references in tuples or other structures
demand characters from whichever stream is needed
6
output must also be incremental for interaction to work
cannot wait for the complete output list before emitting its prefix
7
write evaluates a character-list expression and emits available characters
a potentially infinite result can therefore produce ongoing output
8
write is an interpreter directive, not a callable Hope function
allowed at the program's top level
cannot appear as an operation inside a function body
9
the book organizes a program around one final write directive
define the functions first
call a main function returning a character list
main constructs the output in the required order
10
this interface severely limits coordinated output to several destinations
shell redirection can choose the destination of standard output
11
input denotes standard input in the expression given to write
elsewhere use read "" in this implementation
12
additional library operations:
num2str / str2num: convert numbers and their textual forms
<>: concatenate lists
argv: list of command-line argument strings
13
Pascal-triangle program has three modes
two arguments n,k: output the chosen binomial coefficient
one argument n: output row n
no arguments: display successive rows on Enter, stopping at EOF
14
start with a Hopeless script header
reuse NextLineRest, NextLine, PascalsTriangleBuild and Cnk
15
NumList2Str builds text from a numeric list
empty list -> empty text
prepend num2str(head), a space and the conversion of the tail
interactive helper receives input characters and remaining triangle rows
16
LineByLine algorithm:
EOF -> empty output
newline -> current row's text followed by processing the next row
other character -> skip it without advancing the triangle
express cases through if or separate pattern equations
prepend a synthetic newline to the input for interactive startup
causes row zero to appear before the first user keypress
17
main dispatches by the shape of argv
[]: interactive helper
[n]: convert n and format the selected row
[n,k]: convert both and format Cnk(n,k)
more arguments: return an explanatory message
final write evaluates main(argv,input) followed by a newline
output strings, not imperative print calls, connect the computation
11.5.14 Currying
Currying turns a tuple-taking function into successive one-argument
functions, while partial application fixes a particular argument.
Higher-order Curry exposes that transformation, and direct curried
definitions make function-producing-function structure explicit.
Detailed notes - 11.5.14: Currying
1
the book marks this and the next section as optional background
2
consider a mathematical function accepting several values
equivalently, it may accept one tuple of those values
3
fixing one argument of f(x,y) creates a one-argument function
if f(x,y)=10*x+y and x=3, the remaining function is 30+y
applying that function to 5 gives 35
4
currying transforms f into a function that performs that first step
curried f takes x and returns the function awaiting y
applying the returned function to y gives f(x,y)
fixing one particular x is partial application of that curried form
distinguish the transformed function from one particular closure
5
the name refers to logician Haskell Brooks Curry
the book mentions other language names honoring him
6
Curry is itself a higher-order function
input type: alpha # beta -> gamma
result type: alpha -> beta -> gamma
Curry f returns lambda x => lambda y => f(x,y)
right-associative arrows make extra parentheses optional
7
example with Func(x,y)=10*x+y
Curry Func: function awaiting x, then y
Curry Func 2: function y -> Func(2,y)
Curry Func 2 3 -> 23
8
define a function in curried form directly
Func x y <= 10*x+y
Func 4 7 -> 47
likewise Func3 x y z <= 100*x+10*y+z
Func3 7 3 6 -> 736
implementation can optimize intermediate function applications
9
curried definitions are conventional in Haskell
tuple-taking definitions remain possible
10
currying prepares the fixed-point example in the next section
its function-producing-function structure is what the example needs
A fixed-point combinator supplies a recursive definition with its own
functional reference: Fix f equals f(Fix f). Laziness allows useful
results without unconditional infinite expansion; this is a recursion
mechanism rather than numerical root finding.
Detailed notes - 11.5.15: The fixed-point combinator
1
letrec allows recursion for a locally named anonymous function
the function still acquires a name through the local binding
2
lambda calculus studies computation through function abstraction / application
fixed-point constructions express recursion without naming each recursive function directly
3
lambda notation in these programming languages comes from that formalism
the chapter gives only a practical illustration
4
fixed-point combinators provide the alternative recursion mechanism
5
separate a recursive algorithm from its recursive reference
give its body a parameter representing the recursive function to use
a fixed-point operation connects that parameter back to the result
fixed point of f: a value x satisfying f(x)=x
6
in lambda-calculus terminology, a combinator is a closed expression
it has no free variables
7
fixed-point equation: Fix f = f(Fix f)
type: (alpha -> alpha) -> alpha
the Hope example implements this equation recursively
with laziness, it can produce useful results without expanding forever
8
summing example uses a function transformer phi
phi receives fn and returns a list-processing function
empty list -> 0
head :: tail -> head + fn(tail)
apply Fix to phi, then apply the resulting function to [1,2,3]
Fix phi expands to phi(Fix phi)
returned closure keeps fn bound to unevaluated Fix phi
first element produces 1 + (Fix phi)[2,3]
repeat for 2 and 3
empty-list branch returns 0 without demanding fn
final result: 1+2+3+0 = 6
9
unconditional expansion would create an infinite nesting
f(f(f(...)))
the supplied transformer need not call itself by a name
the recursive connection is supplied by Fix
10
a strict function can make that expansion diverge
if f requires its argument before returning any result, evaluation immediately demands another Fix f
11
the sum transformer avoids that demand initially
returns a function before needing the recursive argument
examines the input list through that function
demands the recursive reference only for a nonempty tail computation
the base case discards the still-suspended remainder
12
Fix is not a numerical root-finding algorithm
x -> 20-x has ordinary numeric fixed point 10
the recursive Fix definition does not solve that equation numerically
a constant function can return its constant without demanding input
13
domain-theoretic fixed points include partial / undefined computations
bottom represents absence of a defined result
least fixed point refers to the information ordering of that model
strict numeric examples can have bottom as the computed fixed point
14
Sumlist is a concrete functional fixed point of phi
phi(Sumlist) returns a function with the same behavior as Sumlist
empty list -> 0; nonempty -> head + Sumlist(tail)
therefore phi(Sumlist)=Sumlist extensionally
Fix phi constructs that same list-summing behavior
15
letrec can be expressed using a fixed point
letrec V == E in B
equivalent to (lambda V => B)(Fix(lambda V => E))
the direct letrec implementation can evaluate it more efficiently
dec YComb : (alpha -> alpha) -> alpha;
! --- YComb f <= let lxfxx == lambda x => f(x x) in lxfxx lxfxx;
! --- YComb <= \ f => (\ x => x x) (\x => f (x x));
--- YComb f <= f(YComb f);
dec fact : num -> num;
--- fact x <=
let almost_fact ==
lambda fn => lambda t =>
if t = 0 then 1 else t * (fn (t-1))
in
(YComb almost_fact) x;
dec id : alpha -> alpha;
--- id x <= x;
! dec fact2 : num -> num;
! --- fact2 x <=
! let
! seed == lambda(fn, t) =>
! (fn, if t = 0 then 1 else t * fn(fn, t-1))
! in
! letrec (f, res) == (YComb seed)(f, x) in res;
dec Memb : (alpha # list(alpha)) -> truval;
--- Memb(m, ls) <=
let seed ==
lambda fn =>
lambda (_, []) => false
| (x, y::rst) =>
if x = y then true else fn(x, rst)
in
YComb seed (m, ls);
dec DropElems : num # list(alpha) -> list(alpha);
--- DropElems(count, lst) <=
let almost ==
\ fn => (\ (_,[])=>[] | (0,ls)=>ls | (k,_::t)=>fn(k-1,t))
in
(YComb almost)(count, lst);
dec Fix : (alpha -> alpha) -> alpha;
--- Fix f <= f(Fix f);
dec Sumlist : list(num) -> num;
--- Sumlist [] <= 0;
--- Sumlist (x :: r) <= x + Sumlist r;
Comments