Functional and Logic Programming

Reading map

Previous: C++ Programming Reading map Next: Scripting and Execution Strategies

Volume III: Paradigms (Chapter 11)Code & tests Chapter diagrams Download editable SVGs

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

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
  • missing conditional expressions / recursion prevented completion

3

McCarthy / Minsky group formed in 1958

  • initially Lisp was separate IBM 704 assembly subroutines

4

universal Turing machine: interpreter expressed as a Turing machine

  • input encodes machine M and its input word W
  • result is the result of running M on W
  • compact implementations may hide complexity in the encoding

5

universal function: same idea for computable functions

  • McCarthy represented both functions and data as lists
  • parentheses supplied a formal notation for writing EVAL
  • initially intended as a theoretical description

6

Stephen Russell translated EVAL into assembly

  • obtained a working Lisp interpreter
  • theoretical list notation became an actual programming syntax

7

Lisp notation: parenthesized lists; whitespace separates elements

  • function call: function first, then argument expressions
  • (+ (* 5 10) (- 55 5)) -> 50 + 50 -> 100
  • (princ "Hello, world!") prints text; (terpri) adds a newline

8

author: unfamiliar syntax becomes readable with practice

  • parenthesized prefix notation survived major changes to Lisp

9

historical accounts mentioned in the book:

  • Herbert Stoyan: early development of Lisp
  • Paul Graham: Revenge of the Nerds

10

McCarthy presented Lisp in a 1960 paper on symbolic expressions

  • many dialects followed, including systems for Lisp machines
  • Lisp now describes a family of languages

11

Common Lisp: work began in 1981; ANSI standard published in 1994

  • author criticizes its size and the effort of implementation
  • implementation extensions still limit source portability
  • author argues that treating Common Lisp as the only Lisp harmed smaller implementations and the language family's reputation

12

domain-specific dialects developed somewhat independently

  • Emacs Lisp: extension language of Emacs
  • AutoLISP: embedded language in AutoCAD

13

book describes dynamic binding in these dialects

  • its difficulties motivate the later discussion of funargs

14

Scheme: first implementation in 1975

  • Sussman / Steele investigated actors and continuations
  • resulting model also provided a compact Lisp dialect
  • SICP helped popularize it
  • comparisons of implementation numbers describe the book's period

15

Steele also participated in other language standardization work

  • author's disapproval is a judgment about those committees

16

book will introduce Common Lisp before Scheme

  • Common Lisp retains features of older Lisp traditions
  • author nevertheless prefers Scheme for practical consideration

17

Scheme reports: R5RS, R6RS, R7RS

  • number identifies the revision of the language report
  • book dates R5RS to 1997 and favours its small specification

18

R6RS used a formal committee / voting process

  • separate language, libraries, appendices and rationale documents
  • author contrasts their combined size with R5RS's 50 pages

19

R6RS final version appeared in 2007

  • author considers the additional complexity damaging
  • some implementers chose to keep targeting R5RS

20

2009: proposal to separate small and large Scheme specifications

  • R7RS-small appeared in 2013
  • intended to complement R6RS
  • author disputes the educational / industrial justification

21

Chicken Scheme, as used in the book, targets R5RS

  • includes useful facilities beyond it as extensions
  • book's claims about relative support describe that period
Tests & experiments (6 files) - 11.1.1: A little history
Section test01 (11-01)In catalog
MakefileMake / 18 lines
MODULES = tape program

SRCMODULES = $(MODULES:=.cpp)
HEADERS = $(MODULES:=.hpp)
OBJMODULES = $(SRCMODULES:.cpp=.o)

CXXFLAGS = -g -Wall -O0 -ansi -pedantic

all: turing

%.o: %.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) -c $< -o $@

turing: turing.cpp $(OBJMODULES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(filter-out %.hpp,$^) -o $@

clean:
    rm -f *.o turing
program.cppC++ / 31 lines
#include "program.hpp"

Program::~Program()
{
    while (first) {
        Item *next = first->next;
        delete first;
        first = next;
    }
}

void Program::Add(const rule &r)
{
    Item *p = new Item(r);

    if (last)
        last->next = p;
    else
        first = p;

    last = p;
}

const rule *Program::Find(int state, char symbol) const
{
    for (const Item *p = first; p; p = p->next)
        if (p->data.state == state && p->data.read == symbol)
            return &p->data;

    return 0;
}
program.hppC++ / 37 lines
#ifndef PROGRAM_H
#define PROGRAM_H

struct rule {
    int state;
    char read;
    char write;
    char move;
    int next;
};

class Program {
    class Item {
    public:
        rule data;
        Item *next;

        Item(const rule &r) : data(r), next(0) {}
    };

    Item *first;
    Item *last;

    // copying is forbidden
    Program(const Program &);
    void operator=(const Program &);

public:
    Program() : first(0), last(0) {}
    ~Program();

    bool Empty() const { return !first; }
    void Add(const rule &r);
    const rule *Find(int state, char symbol) const;
};

#endif
tape.cppC++ / 84 lines
#include <stdio.h>
#include "tape.hpp"

void Tape::Append(char symbol)
{
    Cell *p = new Cell(symbol);

    if (last) {
        last->right = p;
        p->left = last;
    } else {
        first = p;
    }

    last = p;
}

void Tape::Prepend(char symbol)
{
    Cell *p = new Cell(symbol);

    if (first) {
        first->left = p;
        p->right = first;
    } else {
        last = p;
    }

    first = p;
}

Tape::Tape(const char *input)
    : first(0), last(0), head(0)
{
    for (const char *p = input; *p; ++p)
        Append(*p);

    if (!first)
        Append(blank);

    head = first;
}

Tape::~Tape()
{
    while (first) {
        Cell *next = first->right;
        delete first;
        first = next;
    }
}

void Tape::Move(char direction)
{
    if (direction == 'R') {
        if (!head->right)
            Append(blank);
        head = head->right;
    } else if (direction == 'L') {
        if (!head->left)
            Prepend(blank);
        head = head->left;
    }
}

void Tape::Print() const
{
    Cell *begin = first, *end = last;

    while (begin && begin->symbol == blank)
        begin = begin->right;
    while (end && end->symbol == blank)
        end = end->left;

    if (!begin) {
        puts("(blank tape)");
        return;
    }

    for (Cell *p = begin; p != end->right; p = p->right)
        putchar(p->symbol);

    putchar('\n');
}
tape.hppC++ / 38 lines
#ifndef TAPE_H
#define TAPE_H

class Tape {
    class Cell {
    public:
        char symbol;
        Cell *left;
        Cell *right;

        Cell(char c) : symbol(c), left(0), right(0) {}
    };

    Cell *first;
    Cell *last;
    Cell *head;

    void Append(char symbol);
    void Prepend(char symbol);

    // copying is forbidden
    Tape(const Tape &);
    void operator=(const Tape &);

public:
    enum { blank = '_' };

    Tape(const char *input);
    ~Tape();

    char Read() const { return head->symbol; }
    void Write(char c) { head->symbol = c; }

    void Move(char direction);
    void Print() const;
};

#endif
turing.cppC++ / 111 lines
#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
    • -> script must use cdddr to skip three elements
  • book mainly uses a shared, classical Lisp subset

9

remaining discussion concerns distributing standalone executables

  • ordinary interpretation is sufficient for the following examples

10

compilation and producing a distributable executable are distinct

  • book compares the implementation-specific delivery procedures

11

SBCL can save a running Lisp image as an executable

  • load application definitions into the running system
  • saved image also contains runtime code and supporting data

12

sb-ext:save-lisp-and-die:

  • required argument: destination filename
  • :executable t makes an executable image
  • :toplevel selects the entry function; otherwise startup uses REPL

13

SBCL example: define main to print the greeting

  • save with :executable t :toplevel 'main
  • process this file with sbcl --load
  • author's resulting executable exceeded 60 MB

14

:compression t reduces the image size

  • author's example: about 12 MB, with visible decompression delay
  • these sizes / timings are measurements of that setup

15

GCL -compile produces an object file

  • this alone does not produce the standalone program being sought

16

GCL can load the compiled object into its Lisp system

  • saving that system normally produces an executable entering REPL

17

GCL example: define si:top-level as the application entry point

  • (compile-file "hello.lsp") -> hello.o
  • (load "hello.o") -> load definitions into the running system
  • (si:save-system "hello") -> save executable and exit
  • author's image was about 12 MB without an observed startup delay

18

ECL can translate Lisp into C and build a program

  • (compile-file "hello.lsp" :system-p t) -> object file
  • c:build-program links the object specified by :lisp-files
  • :epilogue-code () avoids entering the usual interactive ending
  • small executable still depends on shared ECL runtime libraries

19

ECL argument list differs between script and compiled execution

  • compiled program lacks the interpreter / -shell prefix
  • cdddr now discards two real arguments
  • -> compiled echo must use cdr instead

20

author criticizes these application-distribution interfaces

  • later I/O examples examine further portability difficulties
Examples & tests (15 files) - 11.1.2: SBCL, GCL and ECL
Book exampleBook example: sbcl_hello_comp.lspIn catalog
sbcl_hello_comp.lspLisp / 11 lines
(defun main ()
    (princ "Hello, world!")
    (terpri)
)

(sb-ext:save-lisp-and-die "sbcl_hello"
    :executable t
    :toplevel 'main
    :compression t
    :purify t
)
Section test02 (11-01)In catalog
_ecl.lspLisp / 3 lines
#!/usr/bin/ecl -shell
(princ "Hello world!")
(terpri)
_gcl.lspLisp / 3 lines
#!/usr/bin/gcl -f
(princ "Hello world!")
(terpri)
_sbcl.lspLisp / 3 lines
#!/usr/bin/sbcl --script
(princ "Hello world!")
(terpri)
args_ecl.lspLisp / 6 lines
#!/usr/bin/ecl -shell
(mapcar
    #'(lambda (arg) (princ arg) (princ " "))
    (cdddr (ext:command-args))
)
(terpri)
args_gcl.lspLisp / 6 lines
#!/usr/bin/gcl -f
(mapcar
    #'(lambda (arg) (princ arg) (princ " "))
    (cdr si::*command-args*)
)
(terpri)
args_sbcl.lspLisp / 6 lines
#!/usr/bin/sbcl --script
(mapcar
    #'(lambda (arg) (princ arg) (princ " "))
    (cdr *posix-argv*)
)
(terpri)
hello_c.cC / 7 lines
#include <stdio.h>

int main()
{
    printf("Hello, World!\n");
    return 0;
}
hello_ecl.lspLisp / 2 lines
(princ "Hello, world!")
(terpri)
hello_gcl.lspLisp / 4 lines
(defun si:top-level ()
    (princ "Hello, World!")
    (terpri)
)
hello_sbcl.lspLisp / 9 lines
(defun main ()
    (princ "Hello, world!")
    (terpri)
)
(sb-ext:save-lisp-and-die "hello_sbcl"
    :executable t
    :compression t
    :toplevel 'main
)
nest0.shShell / 30 lines
#!/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"
nest1.shShell / 22 lines
#!/bin/sh

# Create a directory containing nested #! interpreter scripts.
dir=$(mktemp -d) || exit 1

for i in 1 2 3 4 5 6 7 8 9; do
    next=$((i + 1))
    printf '#!%s/s%s\n' "$dir" "$next" > "$dir/s$i"
done

printf '#!/bin/sh\necho "Reached the end"\n' > "$dir/s10"
chmod +x "$dir"/s*

printf 'Scripts created in: %s\n' "$dir"
printf '\nRunning s1 (too many nested interpreters):\n'
"$dir/s1"

printf '\nRunning s7 (shorter chain):\n'
"$dir/s7"

printf '\nInspect them with: ls -l %s\n' "$dir"

nest2.shShell / 17 lines
#!/bin/sh
# nest.sh: s1 has s0 as its interpreter, s2 has s1, and so on
#   usage: sh nest.sh

dir=$(mktemp -d)
cd "$dir" || exit 1
printf '#!/bin/sh\necho "works: $0 $*"\n' > 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"
nest3.shShell / 17 lines
#!/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
A cons cell contains a head and a tail. Sharing is safe while the shared cells remain unchanged.
Two lists can share a tail without copying it. Open full size - Editable SVG
Tests & experiments (2 files) - 11.1.3: S-expressions: a heterogeneous data model
Section test03 (11-01)In catalog
sexptr.lspLisp / 26 lines
; 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))
shared.lspLisp / 12 lines
#!/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

  • 25 -> 25; #\A -> #\A; "Simple string" -> that string

3

nil and t are constant symbols evaluating to themselves

  • nil means false; every non-nil value counts as true
  • other constant symbols may have fixed values, such as pi

4

ordinary symbol -> look up its value in the current environment

  • an unbound symbol normally causes an error
  • some older dialects instead supplied a default value

5

an evaluable list is called a form

  • normally a proper list; an improper list is not a valid call form

6

first element usually names the operation

  • a lambda expression can also appear in function position

7

ordinary function call: evaluate arguments, then apply the function

  • (* (+ 3 7) 5 (- 6 4))
  • argument values: 10, 5, 2 -> multiplication returns 100

8

function call is only one possible interpretation

  • a leading symbol can instead designate a macro / special form

9

Lisp macro: constructs another form from unevaluated argument forms

  • expansion code runs as Lisp code
  • its result is code to evaluate, rather than the final answer
  • expansion can occur before the resulting program runs

10

book omits macro programming details

  • author's point: macro systems need not share C macros' weaknesses

11

special forms have individual evaluation rules

  • can leave arguments unevaluated, select branches or bind names
  • language defines the primitive special operators
  • macros build additional constructs from those primitives

12

following examples use a small selection of built-in facilities

  • the complete Common Lisp library is much larger

13

quote: return the supplied expression without evaluating it

  • (quote (1 2 3)) = '(1 2 3)
  • (f '(1 2 3)) passes a list; (f (1 2 3)) attempts an invalid call
  • 'x gives the symbol X rather than its variable value

14

arithmetic uses prefix function calls

  • + / * combine arguments; unary - changes sign
  • (/ 2 3) can return exact rational 2/3
  • <, >, =, <=, >=, /= compare numbers

15

not returns t only for nil

  • and evaluates left to right, stopping at the first nil
    • -> otherwise returns the last argument's value
  • or stops at the first non-nil value and returns it
    • -> returns nil if no argument succeeds

16

and / or cannot be ordinary eager functions

  • later arguments may remain unevaluated
  • this also determines whether their side effects happen

17

Common Lisp implements and / or as macros

  • conditional evaluation can be expressed using if

18

cons constructs a new pair from two argument values

  • (cons 1 (cons 2 (cons 3 nil))) -> (1 2 3)
  • a pair is also commonly called a cons

19

car returns the left part; cdr returns the right part

  • (car '(1 2 3)) -> 1
  • (cdr '(1 2 3)) -> (2 3)

20

historical background: IBM 704 had 36-bit words

  • magnetic-core memory; addresses fitted into 15 bits

21

its instruction formats included address and decrement fields

  • some instructions held a 15-bit immediate / decrement value

22

assembly macros extracted those instruction fields

  • CAR: contents of the address part of the register
  • CDR: contents of the decrement part of the register
  • register here used the older, broader meaning of a storage cell

23

Lisp pairs reused the two address-sized fields

  • extraction routines inherited the CAR / CDR macro names
  • book distinguishes these macros from machine instruction names

24

alternative names exist: first / rest, head / tail

  • car / cdr remain established Lisp terminology

25

list constructs a proper list of its evaluated arguments

  • (list 'a 'b 'c) -> (A B C)

26

predicates for the pair / atom model:

  • listp: true for nil or any cons, including improper lists
  • atom: true exactly when the value is not a cons
  • null: tests for nil; same truth result as not

27

if: evaluate condition, then exactly one selected branch

  • (if (> x 0) (f x) (g (- x)))
  • positive x -> f(x); otherwise -> g(-x)
  • missing false branch returns nil when the condition is false

28

cond supports several alternatives and several forms per alternative

  • author observes a preference for cond in the Lisp code discussed

29

cond clauses: (condition body-form ...)

  • test conditions in order; choose the first non-nil result
  • evaluate that clause's body; return its last value
  • condition-only clause returns its successful condition value
  • no successful clause -> nil

30

final clause headed by t acts as a default

  • reached only when all earlier conditions were false

31

the two-branch if can also be written using cond

  • ((> x 0) (f x)) followed by (t (g (- x)))

32

eq compares identity: physically the same object

  • useful for symbols; identical-looking separate lists need not match

33

eql adds same-type numeric equality and character equality

  • do not rely on an implementation making equal numbers eq
  • distinct equal strings are not eql in Common Lisp

34

eql differs from numeric =

  • (= 2 2.0) -> t; (eql 2 2.0) -> nil
  • integer and floating-point objects have different types

35

equal also compares list structure recursively

  • compares corresponding car / cdr values
  • includes string / bit-vector content comparison in Common Lisp
  • do not infer deep comparison of every possible object type

36

additional operations will be introduced when examples require them

Evaluation interprets a form; quotation returns its structure without evaluating that form.
The same list can be program structure or data. Open full size - Editable SVG
Section test (1 file) - 11.1.4: Evaluating S-expressions
Section test04 (11-01)In catalog
cond.lspLisp / 14 lines
(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
Section test05 (11-01)In catalog
funcs.lspLisp / 43 lines
(defun sqe-discrim (a b c)
  (- (* b b) (* 4 a c))
)

(defun length1 (lst)
    (cond
        ((atom lst) 0)
        (t (+ 1 (length1 (cdr lst))))
    )
)

(defun length2 (lst)
    (cond
        ((null lst) 0)
        ((atom lst) nil)
        ((atom (cdr lst)) 1)
        (t (+ 1 (length2 (cdr lst))))
    )
)

(defun length3_do (lst len)
    (cond
        ((atom (cdr lst)) len)
        (t (length3_do (cdr lst) (+ 1 len)))
    )
)

(defun length3 (lst)
    (cond
        ((null lst) 0)
        ((atom lst) nil)
        (t (length3_do lst 1))
    )
)

(defun reverse1_do (lst res)
    (cond
        ((null lst) res)
        (t (reverse1_do (cdr lst) (cons (car lst) res)))
    )
)

(defun reverse1 (lst) (reverse1_do lst ()))

11.1.6 Destructive 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
Section test06 (11-01)In catalog
copy.lspLisp / 6 lines
(defun copylist (lst)
    (cond
        ((atom lst) lst)
        (t (cons (car lst) (copylist (cdr lst))))
    )
)

11.1.7 The eval function

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
  • (eval (list 'cdr '(list 1 2 3)))
    • -> constructs (cdr (list 1 2 3)) -> evaluates it -> (2 3)

2

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

  • maps addition over (1 2 3 4), (10 20 30 40), (100 200 300 400) -> (111 222 333 444)
  • mapping list instead -> ((1 10 100) (2 20 200) ...)
  • results form a new list

10

named plus3 can add 3 to each element through mapcar

  • many tiny named helpers become awkward
  • fixed definition also does not solve a runtime-selected increment

11

lambda creates an anonymous function

  • avoids requiring a separate name
  • free variables can refer to the enclosing environment

12

lambda expression: lambda, parameter list, body forms

  • ((lambda (a b c) (+ a (* b c))) 10 3 5) -> 25
  • #'(lambda (x) (+ 3 x)) can be passed to mapcar
  • add-to-list(num,lst) maps #'(lambda (x) (+ x num)) over lst
  • num comes from the enclosing call's parameter binding

13

returning functions: make-adder(n) returns #'(lambda (x) (+ n x))

  • make-adder(13) creates a function that adds 13
  • store it as plus13's variable value; (funcall plus13 77) -> 90
  • no quote needed: evaluating plus13 already gives the function

14

function and variable bindings are separate in Common Lisp

  • placing that object in (symbol-function 'plus13) permits ordinary call syntax: (plus13 77)

15

ordinary functions cannot decide whether to evaluate their arguments

  • mapcar / apply already supply computed data values
  • a function cannot treat the same interface sometimes as source forms and sometimes as already computed arguments

16

ordinary call evaluation therefore computes argument values first

  • same application operation is usable by higher-order functions
  • macros / special operators control evaluation and cannot be used interchangeably with ordinary function objects
Section test (1 file) - 11.1.8: Functions as objects
Section test08 (11-01)In catalog
lambda.lspLisp / 7 lines
(defun add-to-list (num lst)
    (mapcar #'(lambda (x) (+ x num)) lst)
)

(defun make-adder (n)
    #'(lambda (x) (+ n x))
)

11.1.9 The funarg problem and lexical binding

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

29

shared counter example:

  • let creates counter = 0
  • seq-next increments and returns counter
  • seq-reset assigns 0 to the same counter
  • successive calls -> 1, 2, 3; reset -> 0; next -> 1
  • binding survives because the defined functions retain it

30

shared private state plus functions resembles an object with methods

  • quoted teaching story contrasts closures and objects
  • point: the two mechanisms can express closely related structures

31

book traces the story to Anton van Straaten's mailing-list posting

  • Russian retellings changed the wording while retaining the idea
The captured binding belongs to the lexical environment, not to the caller that invokes the closure.
A closure keeps the environment of its creation. Open full size - Editable SVG
Tests & experiments (7 files) - 11.1.9: The funarg problem and lexical binding
Section test09 (11-01)In catalog
downward_funard.lspLisp / 9 lines
(defvar thevar)

(defun f2 (func thevar) 
    (funcall func thevar)
)

(defun sample (thevar)
    (f2 #'(lambda (x) (+ x thevar)) 1000)
)
let.lspLisp / 9 lines
(setq thelist '(1 2 3 4 5))

(let ((s 0) (p 1))
    (mapcar
        #'(lambda (x) (setq s (+ s x)) (setq p (* p x)))
        thelist
    )
    (cons s p)
)
let2.lspLisp / 11 lines
(setq thelist '(1 2 3 4 5))

(let (s p)
    (setq s 0)
    (setq p 1)
    (mapcar
        #'(lambda (x) (setq s (+ s x)) (setq p (* p x)))
        thelist
    )
    (cons s p)
)
let3.lspLisp / 4 lines
(let ((counter 0))
    (defun seq-next () (setq counter (+ 1 counter)))
    (defun seq-reset () (setq counter 0))
)
lexical.lspLisp / 9 lines
(shadow 'var)

(defun var-values (var)
  (cons var (symbol-value 'var)))

(setq var "global")

(var-values "local")
;; => ("local" . "global")
test.elLisp / 21 lines
;; -*- lexical-binding: t; -*-
(defun make-adder (thevar)
    #'(lambda (x) (+ thevar x))
)

(setq thevar 100)

(setq plus5 (make-adder 5))

(funcall plus5 10)











upward_funarg.lspLisp / 10 lines
(defvar thevar)

(defun make-adder (thevar)
    #'(lambda (x) (+ thevar x))
)

;; (setq thevar 100)

(setq plus5 (make-adder 5))

11.1.10 The funarg problem in other languages

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
  • captured locals require additional lifetime / access machinery

4

nested Pascal procedures need access to enclosing activations

  • implementation may use static links / displays between frames
  • book relates this to i386 ENTER's nesting operand

5

book's Pascal history: procedural parameters precede general variables

  • passing a nested routine downward keeps its creator active
  • forbidding returned routines excludes the upward lifetime problem

6

implementations later added procedural / functional variable types

  • resemble function pointers for routines without captured context

7

downward use can retain a live enclosing stack frame

  • implementation must still pass / recover the correct environment

8

upward use outlives that frame

  • returned code address alone cannot preserve its former locals
  • requires a different representation and lifetime arrangement
  • author's rejection of this in compiled languages is a design preference, not a general impossibility of compiled closures

9

Pascal implementations discussed restrict ordinary procedural values

  • top-level routines have no disappearing local environment
  • nested-routine support depends on the implementation / routine type

10

standard C has function pointers but no nested functions

  • GCC nested functions are an extension
  • author advises against relying on them

11

GNU C sumprod example has nested plus, times and reduce

  • they share the enclosing automatic variable accum
  • sum starts at 0; product starts at 1
  • direct nested calls can pass an enclosing-frame pointer in a hidden register / argument; book illustrates i386 ECX

12

taking a nested function's address also needs its environment

  • illustrated GCC implementation creates a stack trampoline
  • trampoline loads the context pointer, then jumps to function code
  • function pointer refers to that trampoline

13

trampoline / captured stack data live only while the creator is active

  • returning the address does not extend either lifetime
  • apparently working calls may merely encounter unreused stack bytes

14

make_adder returning a nested adder is therefore invalid after return

  • one call may appear to yield 13
  • creating adders for 3 and 7 may reuse the same stack locations
    • -> observed 17 / 17 is possible, not a guaranteed result

15

an intervening call can overwrite the stale trampoline

  • eraser's local array demonstrates this reuse
  • author's run terminated with an illegal-instruction error

16

descending callbacks still raise implementation concerns

  • traditional trampolines require executable stack memory
  • alternative function descriptors have ABI / compatibility costs
  • neither technique alone makes expired captured locals valid

17

author recommends avoiding nested routines in these low-level languages

  • explicit environment objects offer a clearer lifetime model

18

C++ member functions also require a context: the target object

  • a bare ordinary function pointer does not encode that object

19

pointer-to-member-function is a separate type

  • invocation explicitly supplies an object using .* or ->*
  • static member functions do not require an object
  • pointer-to-member alone is not a closure retaining object lifetime
Tests & experiments (3 files) - 11.1.10: The funarg problem in other languages
Section test10 (11-01)In catalog
adder.cC / 17 lines
#include <stdio.h>

typedef int (*funcptr)(int);

funcptr make_adder(int a)
{
    int adder(int t) { return t+a; }
    return &adder;
}

int main()
{
    funcptr a3 = make_adder(3);
    funcptr a7 = make_adder(7);
    printf("%d %d\n", (*a3)(10), (*a7)(10));
    return 0;
}
adder2.cC / 25 lines
#include <stdio.h>

typedef int (*funcptr)(int);

funcptr make_adder(int a)
{
    int adder(int t) { return t+a; }
    return &adder;
}

void eraser(funcptr ff)
{
    char c[50];
    int i;
    for(i = 0; i < sizeof(c); i++)
        c[i] = i;
    printf("%d\n", (*ff)(10));
}

int main()
{
    funcptr a3 = make_adder(3);
    eraser(a3);
    return 0;
}
extension.cC / 28 lines
#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, &times); *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

  • empty list returns init
  • recursive call is in tail position
  • rreduce instead computes fun(car, reduction-of-cdr)
    • -> combination remains after recursion returns

3

right-fold cons with nil copies the list spine

  • (1 2 3) -> new cons cells containing the same elements
  • left-fold cons with nil -> (((nil . 1) . 2) . 3)
  • addition / multiplication folds use 0 / 1 as initial values
  • for these variadic operations, apply is often simpler

4

left-fold lambda(acc,x) = cons(x,acc) reverses a list

  • (1 2 3) -> (3 2 1)
  • using that function in a right fold instead creates nested pairs

5

further fold examples:

  • maximum: initial car, fold larger-of-two over cdr
    • -> requires a nonempty list
  • ins2list inserts into an already sorted list
    • -> stop at nil or first larger element; otherwise copy prefix
  • fold insertion from nil -> insertion sort
    • -> swap combiner arguments when changing fold direction
  • redmap: right-fold cons(funcall(fun,x), accumulated-results)
    • -> mapping unary - over (1 2 3) gives (-1 -2 -3)

6

filtering with a right fold:

  • predicate true -> cons element onto accumulated result
  • false -> retain accumulated result unchanged
  • select numbers from (1 2 "abc" t 15) -> (1 2 15)
  • preserves the order of retained elements
Both take a function as an argument, but they organize the computation differently.
Map preserves the shape; fold summarizes the sequence. Open full size - Editable SVG
Book example (1 file) - 11.1.11: Reducing lists
Book exampleBook example: reduce.lspIn catalog
reduce.lspLisp / 46 lines
(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

8

book first develops normal stream / EOF handling

  • then adds explicit condition handling

9

standard stream variables:

  • *standard-input*, *standard-output*, *error-output*
  • additional streams include *trace-output*, *query-io*, *debug-io* and *terminal-io*

10

actual terminal routing varies by implementation / startup mode

  • author's tests found several named streams sharing destinations
  • reported GCL diagnostic routing describes the tested version

11

many I/O calls accept stream designators

  • nil / omitted stream: standard input or output as appropriate
  • t: terminal I/O for the ordinary reader / printer functions
  • pass an explicit stream when its destination matters

12

prin1, print, pprint and princ take an object and optional stream

  • (prin1 x *error-output*) directs output to the diagnostic stream

13

prin1 prints a readable Lisp representation when possible

  • string includes quotation marks
  • character may appear as #\A or #\Newline

14

print adds a preceding newline and a trailing space

  • pprint performs pretty printing with layout decisions
  • author considers the historical collection of interfaces awkward

15

princ prints strings without surrounding quotes

  • prints characters as characters, including actual newline characters
  • useful for user-facing text

16

terpri writes a newline to the selected output stream

  • stream argument may be omitted for standard output

17

format uses a control string with ~ directives

  • format with nil destination returns a constructed string
  • t destination means standard output for format

18

read is a Lisp parser, not a general numeric-input routine

  • an unmatched opening parenthesis makes it wait for more input
  • malformed input can signal reader conditions
  • user interface must define and handle its own expected format

19

customizing the Lisp reader can support specialized file formats

  • author recommends separating controlled program data from input supplied by users, whose validity cannot be assumed

20

read-char obtains one character

  • (read-char stream nil nil) returns nil at EOF
  • alternative sentinel such as 'eof distinguishes EOF from characters

21

line-length example uses a recursive character-processing loop

  • EOF -> finish
  • newline -> print accumulated length; continue with 0
  • other character -> continue with length + 1
  • unfinished final line is not printed by this particular example

22

Ctrl-C behaviour is implementation-dependent

  • book's tested script runtimes could emit diagnostics / enter debugger
  • later handler explicitly addresses SBCL's interrupt condition

23

read-line returns text without its newline

  • extra return value reports whether EOF ended the line
  • multiple-value facilities are needed to inspect that information

24

open returns a file stream; default direction is input

  • standard Common Lisp does not provide a portable Unix socket API
  • implementations may offer extensions for additional stream sources

25

filename designator can be a string, pathname or stream

  • pathname objects have their own supporting operations

26

keyword call syntax: keyword followed by its value

  • (f :weirdnum 13) supplies 13 for :weirdnum
  • omitted keyword parameters use their defaults

27

keyword symbols also occur as values

  • they evaluate to themselves
  • ordinary symbols used as data usually require quotation

28

open directions include :input, :output, :io and :probe

  • (open "file.txt" :direction :output) requests output
  • :probe returns a closed stream when the probe succeeds

29

checking existence before opening creates a race

  • another process can remove / replace the file between operations
  • handle the actual open result instead of trusting an earlier probe

30

successful open supplies a stream usable by printers

  • failures may signal conditions requiring handlers

31

open policies distinguish existing and missing files

  • :if-exists :overwrite writes from the beginning
    • -> it does not promise truncation of an existing trailing suffix
  • :append writes at the end; nil declines to open an existing file
  • :if-does-not-exist accepts :error, :create or nil
  • input example: (open "file.txt" :if-does-not-exist nil)
  • permission / other failures still need condition handling

32

close closes a stream

  • optional :abort requests abort-related closing behaviour

33

binary streams use an element type suitable for integer elements

  • byte-oriented example: :element-type '(unsigned-byte 8)
  • write-byte receives integer and stream
  • read-byte receives stream and optional EOF controls

34

condition handling gives application code control over I/O failures

35

Common Lisp conditions support more than simple exception unwinding

  • book limits discussion to handler-case

36

handler-case evaluates a protected form

  • clauses specify condition type, bound condition variable and body
  • (file-error (er) ...) handles a matching file-error
  • progn can group several protected operations

37

condition objects belong to a type hierarchy

  • handler for a general type can cover more specific condition types
  • author criticizes the coupling to the object system

38

file-error-pathname retrieves the associated pathname

  • portable interface does not expose every OS-specific failure detail
  • book probes SBCL internals to extract a diagnostic string
  • private slots / localized strings are unsuitable as stable error codes; the example is specific to the author's tested version

39

book reports different limitations in tested ECL / GCL versions

  • these observations should not be read as current compatibility guarantees for every implementation version

40

princ can print a condition's human-readable report

  • its wording comes from the implementation
  • report text alone is not a portable structured recovery interface

41

worked application: print lengths of lines from a selected file

  • fall back to standard input when no filename is supplied

42

SBCL script builds on the earlier recursive character loop

  • do_it(file,len) accepts its input stream explicitly
  • process_stdin calls it with *standard-input* and zero length

43

opening a file and later signalling a condition can skip plain close

  • resource cleanup must also work on abnormal exit

44

with-open-file binds the newly opened stream and evaluates its body

  • closes the stream on normal completion or nonlocal exit
  • accepts the relevant open options

45

complete example combines opening, processing and handlers

  • process_file uses :if-does-not-exist nil
    • -> nil stream: print application diagnostic
    • -> valid stream: call do_it
  • *posix-argv* selects filename or standard input
  • file-error handler prints a concise report to *error-output*
  • sb-sys:interactive-interrupt handler ends quietly on Ctrl-C
  • interrupt condition name and argument access are SBCL-specific
Book examples (2 files) - 11.1.14: Input and output
Book exampleBook example: strlens_file.lspIn catalog
strlens_file.lspLisp / 97 lines
#!/usr/bin/sbcl --script

(defun do_it (file len)
    (let ((c (read-char file nil nil)))
        (cond
            ((eq c nil) t)
            ((eq c #\Newline) (prin1 len) (terpri) (do_it file 0))
            (t (do_it file (+ 1 len)))
        )
    )
)

; (defun process_file (fname)
;     (princ fname)
;     (terpri)
;     (with-open-stream
;         (f (open fname :direction :input :if-does-not-exist nil))
;         (if (null f)
;             (progn
;                 (princ "Couldn't open the file" *error-output*)
;                 (terpri *error-output*)
;                 nil
;             )
;             (do_it f 0)
;         )
;     )
; )

(defun process_file (fname)
    (with-open-file (f fname :direction :input :if-does-not-exist nil)
        (if (null f)
            (progn
                (princ "Couldn't open the file" *error-output*)
                (terpri *error-output*)
                nil
            )
            (do_it f 0)
        )
    )
)

(defun process_stdin ()
    (do_it *standard-input* 0)
)

; (let
;     ((lst
;         (multiple-value-list (ignore-errors
;             (if (cdr *posix-argv*)
;                 (process_file (second *posix-argv*))
;                 (process_stdin)
;             )
;             t
;         ))
;     )) ;;
;     (if (not (car lst))
;         (progn
;             (princ "Something went wrong" *error-output*)
;             (terpri *error-output*)
;             (princ (second lst) *error-output*)
;             (terpri *error-output*)
;             (prin1 (second lst) *error-output*)
;             ;(inspect (second lst))
;             ;(terpri *error-output*)
;             (princ
;                 (third (slot-value (second lst) 'sb-kernel::format-arguments))
;                 *error-output*
;             )
;             (terpri *error-output*)
;             (princ "The exception type is: " *error-output*)
;             (princ (type-of (second lst)) *error-output*)
;             (terpri *error-output*)
;             (princ
;                 (if (typep (second lst) 'file-error)
;                     "Yes, it is file error!"
;                     "No, it is not a file error. Strange."
;                 )
;                 *error-output*
;             )
;             (terpri *error-output*)
;             nil
;         )
;     )
; )

(handler-case
    (if (cdr *posix-argv*)
        (process_file (second *posix-argv*))
        (process_stdin)
    )
    ;;
    (file-error (er)
        (princ er *error-output*)
        (terpri *error-output*)
    )
    (sb-sys:interactive-interrupt () nil)
)
Book exampleBook example: textbychar.lspIn catalog
textbychar.lspLisp / 13 lines
#!/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

1

author values Scheme's relatively compact specification

  • 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

  • (import (chicken process-context)) supplies argument access
  • echo maps a printing function over command-line-arguments

8

book also mentions argv

  • its script / compiled differences make it less convenient here

9

-ss script mode calls main with the argument list

  • define main(args) and place application work there
  • loading definitions into REPL need not run the application

10

compiling the -ss arrangement needs an explicit main call

  • book supplies it through csc's -postlude option
  • postlude evaluates (main (command-line-arguments))

11

small default executables depend on Chicken runtime libraries

  • book's static-build example uses -static and -strip
  • -x / -uses library select runtime components in that version
  • omits eval support when runtime evaluation is unnecessary
  • author's approximately 2 MB echo is a setup-specific measurement
Book example (1 file) - 11.2.1: Chicken Scheme
Book exampleBook example: hello.scmIn catalog
hello.scmScheme / 4 lines
#!/usr/bin/csi -is

(display "Hello, world!")
(NEWLINE)

11.2.2 Visible differences from traditional Lisp

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

1

Scheme separates the empty list from false

  • () is the empty list; #t / #f are boolean objects
  • only #f is false; even () counts as true
  • nil has no special built-in meaning

2

naming conventions expose the kind of operation

  • predicates end in ?: null?, number?, pair?
  • mutation ends in !: set!, set-car!, set-cdr!
  • conversions: string->list, number->string, char->integer
  • type-specific comparisons: char=?, string>?, etc.

3

map corresponds to Common Lisp's mapcar

  • for-each runs the procedure for effects without building a result list; its calls occur in list order

4

several operations have unspecified results

  • examples: set!, define, display, for-each
  • an if without an else cannot supply a meaningful value when false
  • unspecified result is distinct from a guaranteed useful value

5

Scheme requires proper tail calls

  • tail position can pass control onward without retaining a frame merely to return the same value

6

if evaluates the condition and transfers to the selected branch

  • selected branch can retain tail position
  • missing false branch supplies no specified useful result

7

Chicken's void produces an unspecified value

  • can explicitly finish an effect-oriented function

8

values returns multiple values; call-with-values receives them

  • (values) produces zero values
  • zero values and one unspecified value are different cases

9

Common Lisp also supports multiple / zero values

  • ordinary single-value contexts use its primary-value conventions

10

remaining differences concern the underlying evaluation model

11

Scheme has one ordinary namespace for variable / function values

  • a function name is a variable whose value is a procedure

12

ordinary application evaluates the operator expression too

  • resulting procedure is applied to the computed operands
  • macros / special syntax still follow their own rules

13

lambda is an expression yielding a closure

  • no Common Lisp function form or #' notation is required

14

funcall is unnecessary

  • where Lisp uses (funcall f a b), Scheme uses (f a b)
  • apply remains useful for arguments supplied as a list

15

define establishes both ordinary values and procedures

  • (define myvar 275)
  • (define (plus3 x) (+ 3 x))
  • shorthand for (define plus3 (lambda (x) (+ 3 x)))

16

definitions belong at top level or in allowed body-definition positions

  • internal definitions introduce local bindings
  • local name shadows a same-named outer binding

17

dotted formal-parameter lists express variable arity

  • (define (myvarfunc x y . rest) ...)
  • at least two arguments; extras collected into rest

18

Common Lisp expresses the same pattern with &rest

  • author prefers Scheme's reuse of existing dotted-list notation

19

author values the smaller set of core constructs

  • contrasts it with Common Lisp coerce, setf and loop

20

Scheme still converts between symbols and strings

  • symbol->string / string->symbol
  • escaped names can contain unusual characters

21

ordinary Scheme bindings are lexical

  • set! changes an existing binding
  • define / let introduce bindings; implementation extensions may accept more than the portable language requires

22

parameter objects provide controlled dynamic binding

  • make-parameter / parameterize interact with dynamic extent
  • continuation re-entry makes that extent more than one time interval
  • fluid-let is an extension, not a universal R7RS core form

23

other characteristic facilities: hygienic macros and continuations

  • book leaves macros aside and develops continuations next
Book example (1 file) - 11.2.2: Visible differences from traditional Lisp
Book exampleBook example: quad_eq.scmIn catalog
quad_eq.scmScheme / 13 lines
(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
strlens_file.scmScheme / 36 lines
#!/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
At the marked point, the waiting context is "add 1 to the value produced here".
A continuation represents the rest of a computation. Open full size - Editable SVG

11.2.5 (*) Continuation-passing style

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.

Detailed notes - 11.2.5: (*) Continuation-passing style

1

CPS makes the next computation an explicit procedure argument

  • after computing a result, call continuation k with it
  • continuation determines where control goes next

2

Pythagorean example: sqrt(x*x + y*y)

  • *&(x,y,k) invokes k(x*y); +& and sqrt& do likewise
  • compute x*x; continuation receives x2
  • compute y*y; next continuation receives y2
  • add x2+y2; next continuation takes its square root
  • final result goes to original k
  • nested lambdas express intermediate continuations explicitly

3

CPS is useful as a compiler representation

  • 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

13

initialization(main) selects startup work

  • book's main/1 arrangement receives command-line arguments
  • 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.

Detailed notes - 11.4.3: Prolog's data model

1

term = a Prolog data expression

  • heterogeneous dynamic structures resemble Lisp S-expressions

2

numeric atomic terms include integers and floating-point values

  • book's SWI build normally supports arbitrary-size integers
  • floating-point representation follows the platform implementation

3

atoms resemble Lisp symbols

  • lowercase-leading letter / digit / underscore names need no quotes
  • 'Hello' requires quotes; unquoted Hello denotes a variable
  • quoted atoms can contain spaces and escaped characters
  • certain punctuation sequences also form unquoted atoms

4

atoms can be tags, compound-term functors or predicate names

  • older Prolog code also uses them as text strings

5

atom is narrower than atomic term

  • numbers are atomic but are not atoms
  • book's newer SWI model treats [] as a special empty-list value

6

SWI also has string objects and blobs

  • blobs carry special data, including foreign-interface objects

7

compound term = functor with arguments

  • date(2019,may,31), person('John Doe',m,1978)
  • analogous to tagged records with positional fields
  • arity = number of arguments

8

arguments can themselves be compound terms

  • circle(point(2,2),1) has principal functor circle
  • nested point has its own functor and two arguments

9

functor name plus arity identifies a compound shape

  • point/2, date/3, place/4
  • same name with different arity describes a different shape

10

an atom can be regarded as a zero-argument functor

  • written without parentheses
  • numbers do not serve as ordinary functor names

11

no whitespace between functor and opening argument parenthesis

  • f(x) is compound syntax; f (x) does not mean the same thing

12

operator notation is an alternative way to write terms

  • op(1000,xfx,loves) permits john loves mary
  • same structure as loves(john,mary)

13

operator declaration gives precedence and associativity

  • lower precedence number binds more tightly
  • xfx: non-associative; yfx: left; xfy: right
  • fx / fy: prefix; xf / yf: postfix

14

arithmetic-looking expressions are also term structures

  • X is 2 * 2 = is(X,*(2,2)) as notation
  • executing a query gives the structure its operational meaning

15

clauses are terms too

  • :-, conjunction comma and disjunction semicolon have operator notation; they are not an unrelated syntax for program text

16

punctuation can additionally act as syntax

  • comma separates arguments / list elements
  • terminating dot ends a clause or query

17

lists consist of head / tail pairs

  • [1|[2|[3|[]]]] = [1,2,3]
  • [1,2,3|4] has a non-list tail and is improper

18

traditional list-pair functor was '.'/2

  • SWI-Prolog 7 changed its internal notation to '[|]'/2
  • '[|]'(1,'[|]'(2,[])) represents [1,2]

19

this naming change does not change the head / tail structure

20

lists can contain different term types and arbitrary nesting

  • suitable unification can also construct cyclic structures

21

traditional double-quoted text often meant a list of character codes

  • "Hello" could mean [72,101,108,108,111]
  • distinct from a dedicated string object

22

SWI introduced string objects before making quoted strings the default

  • book describes the transition through versions 3, 6 and 7
  • set_prolog_flag(double_quotes,string) selects string interpretation

23

quote interpretation is configurable

  • double_quotes modes include string, codes, chars and atom
  • back_quotes has related implementation-specific settings

24

SWI 7 defaults described by the book:

  • double quotes -> string; backquotes -> code list
  • --traditional restores older parsing conventions

25

dedicated text values avoid conflating text with program identifiers

  • atom interning has lookup / uniqueness overhead
  • some implementations also restrict atom-name length

26

code lists have their own costs

  • indistinguishable from ordinary integer lists without context
  • multiple list cells consume more memory than compact text
  • traversal / allocation / garbage collection add overhead

27

author welcomes the distinction but questions why it arrived so late

28

variables start with uppercase letters or underscore

  • examples: X, Person, _list, F15

29

variable scope is one clause or query instance

  • may be free or bound to a term, including one with variables
  • backtracking can undo bindings made while exploring an alternative

30

binding is not imperative reassignment

  • a free variable acquires a binding
  • later incompatible requirements fail instead of replacing its value
Matching proceeds through the structure of both terms; repeated variables must agree everywhere.
Unification finds a consistent substitution. Open full size - Editable SVG

11.4.4 Unifying terms

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

18

facts explicitly list satisfying cases

  • simplest way to define a finite relation

19

family example:

  • parent("Mary","Ann"); parent("Mary","John")
  • parent("George","John")
  • male("George"), male("John"); female("Mary"), female("Ann")
  • each fact is a separate term ending with a dot

20

fact-based relations often act as the program's database

  • rules supply the processing logic

21

SWI can also modify dynamic rules at runtime

  • author recommends retaining a clear distinction between program logic and changing data
Facts are tried in order; failure resumes the most recent remaining choice.
Backtracking explores alternatives and undoes bindings. Open full size - Editable SVG

11.4.6 Rules and procedures

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
Book exampleBook example: small_ex.plIn catalog
small_ex.plProlog / 87 lines
:- set_prolog_flag(double_quotes, string).

:- dynamic parent/2.

parent("Lucas", "Mary").
parent("Lucas", "Jason").
parent("Lucas", "Peter").
parent("Mary", "Fred").
parent("Mary", "Jane").
parent("Jason", "Sean").
parent("Jason", "Jessica").
parent("Jason", "Hannah").
parent("Jessica", "Joseph").
parent("Jessica", "John").
parent("Jessica", "Laura").

ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).

sibling(A, B) :- parent(X, A), parent(X, B), A \= B.


plays("John", football).
plays("George", football).
plays("Sam", football).
plays("George", chess).
plays("Mary", chess).
plays("Sam", baseball).

learns("John", chemistry).
learns("John", biology).
learns("Sam", math).
learns("Sam", biology).
learns("George", history).
learns("Ann", law).

interesting(Pers) :- learns(Pers, _), plays(Pers, _).
student_plays(Pers, Game) :-
    learns(Pers, _), plays(Pers, Game).



del_any(_, [], []).
del_any(Elem, [Elem|Tail], Res) :- del_any(Elem, Tail, Res).
del_any(Elem, [X|Tail], [X|NewT]) :- del_any(Elem, Tail, NewT).

del_any_inv(_, [], []).
del_any_inv(Elem, [X|Tail], [X|NewT]) :- del_any_inv(Elem, Tail, NewT).
del_any_inv(Elem, [Elem|Tail], Res) :- del_any_inv(Elem, Tail, Res).

del_all(_, [], []).
del_all(Elem, [Elem|Tail], Res) :-
    del_all(Elem, Tail, Res).
del_all(Elem, [X|Tail], [X|NewT]) :-
    not(X = Elem),
    del_all(Elem, Tail, NewT).

del_all_cut(_, [], []) :- !.
del_all_cut(Elem, [Elem|Tail], Res) :- !, del_all_cut(Elem, Tail, Res).
del_all_cut(Elem, [X|Tail], [X|NewT]) :- del_all_cut(Elem, Tail, NewT).

del_all_ifthen(_, [], []).
del_all_ifthen(Elem, [X|Tail], Res) :-
    Elem = X ->
        del_all_ifthen(Elem, Tail, Res) ;
        del_all_ifthen(Elem, Tail, NewT) , Res = [X|NewT].

listlen([], 0).
listlen([_|T], L) :- listlen(T, TL), L is TL + 1.

prefix([], _, 0).
prefix([H|T2], [H|T], N) :- N2 is N - 1, prefix(T2, T, N2).

prefix2([], _, 0).
prefix2([H|T2], [H|T], N) :- nonvar(N), N2 is N - 1, prefix2(T2, T, N2).
prefix2([H|T2], [H|T], N) :- var(N), prefix2(T2, T, N2), N is N2 + 1.


join([], L, L).
join([H|T], L, [H|M]) :- join(T, L, M).


listrev(L, R) :- listrev(L, R, []).

listrev([], A, A).
listrev([H|T], R, A) :- listrev(T, R, [H|A]).

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
  • del_any(1,[1,2,1,3,1],L) explores eight keep/delete choices

13

clause order determines answer order

  • delete clause first -> answers deleting an earlier match first
  • swapping delete / keep clauses reverses that preference

14

the same relation can check a proposed result or infer the deleted value

  • del_any(X,[1,2,1,3,1],[1,2,3]) finds X = 1
  • del_any(X,[1,2,3],[1,2]) finds X = 3
  • with only Source fixed, enumerate possible deletions and results
  • unchanged Source can leave Element unbound

15

reconstructing Source introduces infinitely many possibilities

  • delete-first search can recurse indefinitely before an answer
  • keep-first order finds [2,3], [2,3,1], [2,3,1,1], ...
  • remains on that infinite branch and never reaches [1,2,3]

16

logical invertibility does not guarantee useful search in every mode

  • termination and control-sensitive built-ins also matter

17

join(A,B,C) means C is A followed by B

  • counterpart of the built-in append relation

18

list representation suggests recursion over the first list

  • second list can be shared as the final tail

19

definition:

  • join([],L,L).
  • join([H|T],L,[H|M]) :- join(T,L,M).
  • matching the result structure in the head avoids a separate result variable and explicit final unification

20

join(X,Y,[a,b,c]) enumerates all splits

  • [], [a,b,c]
  • [a], [b,c]
  • [a,b], [c]
  • [a,b,c], []

21

listrev/2 uses listrev/3 with an initially empty accumulator

  • base: listrev([],A,A)
  • step: listrev([H|T],R,A) calls listrev(T,R,[H|A])
  • forward mode reverses the supplied list
  • reverse mode finds the intended answer, then may search forever if asked for additional answers

22

finding a correct first solution is not enough for reliable enumeration

  • subsequent search can still diverge

23

inside another procedure, later failure may demand another answer

  • there is no interactive user to stop the unnecessary search

24

next section changes control flow to avoid this divergence

  • illustrates the difference between relation and search procedure
append(A,B,C) relates a prefix, a suffix and their concatenation.
One relation can be queried in several directions. Open full size - Editable SVG

11.4.8 Negation and cut

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 []

  • recursive clause keeps adding arbitrary heads indefinitely

20

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

  • example rational expression: 2 rdiv 3

2

arithmetic notation initially constructs ordinary terms

  • -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

  • current_input / current_output designate implicit I/O destinations
  • changing an association does not assign a value to the atom itself

17

explicit-stream versions add the stream as first argument

  • write(user_output,Text); write(user_error,Diagnostic)
  • distinguishes selected standard destinations from current output

18

open takes filename, mode, result stream and optional option list

  • SWI also offers extensions such as opening a pipe to a command

19

modes: read, write, append, update

  • write starts fresh / truncates
  • update writes over existing contents without initially clearing it

20

result argument obtains a stream object

  • book also discusses establishing an atom alias for the opened stream

21

even user_* aliases can be reassociated

  • set_stream(Stream,alias(user_output)) changes that association

22

fourth argument is a list of stream options

  • book explicitly chooses [encoding(octet)] for byte interpretation
  • text applications instead need their intended encoding

23

close closes a stream

  • book describes special treatment of initial standard streams
  • closing reassociated aliases can restore their original streams

24

author considers explicit-stream I/O closer to the desired OS model

  • error handling still requires separate treatment

25

I/O errors are exceptions rather than ordinary goal failure

  • ordinary failure would undo bindings used to return error details

26

throw(Term) raises an exception

  • catch(Goal,Pattern,Handler) executes Goal
  • matching exception unifies with Pattern and runs Handler
  • unmatched exception propagates outward
  • handler can use variables bound while matching the exception

27

built-in errors commonly use error(Formal,Context)

  • examples: existence_error, permission_error, io_error
  • formal term classifies the error; context carries further details

28

book's observed diagnostic wording / locale behaviour is version-specific

  • structured error categories are preferable to parsing message text

29

worked line-length program:

  • reading(Stream,N) reads a code and calls handle(Stream,Code,N)
  • EOF -> stop; newline -> print N and continue with 0
  • other code -> increment N and continue
  • error handler decomposes error terms and writes to user_error
  • process_file opens with octet encoding and protects work with catch
  • main configures prompt / SIGINT, chooses filename or standard input
  • halt ends execution; this example omits explicit file closing
  • only newline-terminated lines cause a length to be printed
Book example (1 file) - 11.4.10: Input and output
Book exampleBook example: strlens_file.plIn catalog
strlens_file.plProlog / 35 lines
#!/usr/bin/swipl -q

:- initialization(main).

handle(_, -1, _) :- !.
handle(Stream, 10, N) :- !, write(N), nl, reading(Stream, 0).
handle(Stream, _, N) :- N1 is N+1, reading(Stream, N1).

reading(Stream, N) :- get0(Stream, C), !, handle(Stream, C, N).

err(error(E, C)) :- !,
    E =.. [ErrorReason|_], C =.. [_, _, Message],
    write(user_error, ErrorReason),
    write(user_error, ' ('),
    write(user_error, Message),
    write(user_error, ')\n'),
    halt.
err(Ex) :-
    write(user_error, 'Exception unknown: '),
    write(user_error, Ex),
    nl(user_error),
    halt.

process_file_on(Fname) :-
    open(Fname, read, Stream, [encoding(octet)]),
    reading(Stream, 0).

process_file(Fname) :- catch(process_file_on(Fname), Ex, err(Ex)).

main :-
    on_signal(int, _, default),
    prompt(_, ''),
    current_prolog_flag(argv, Argv),
    (Argv = [Fname|_], process_file(Fname) ; reading(user_input, 0)),
    halt.

11.4.11 Analysing atoms and terms

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
A suspended computation is evaluated only when demanded; later uses can reuse the value.
Lazy evaluation delays work and shares its result. Open full size - Editable SVG

11.5.2 Hope and other lazy languages

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

  • (25, 'a', true): num # char # truval
  • # combines component types; commas combine component values

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
Book example (1 file) - 11.5.6: Functions in Hope
Book exampleBook example: small_ex.hopIn catalog
small_ex.hopHope / 48 lines
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
Book exampleBook example: strwords.hopIn catalog
strwords.hopHope / 30 lines
! 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
  • the algorithm need not know either concrete type

5

map type: (alpha -> beta) # list(alpha) -> list(beta)

  • empty list -> empty list
  • nonempty list -> f(head) :: map(f,tail)

Times10 example maps [1,2,3,4] to [10,20,30,40]

  • lambda x => 10*x avoids a separate named function
  • backslash can abbreviate lambda

functions can also return closures:

  • MakeAdder x returns lambda y => x+y
  • MakeAdder 21 produces a function adding 21
  • applying it to 19 gives 40
  • 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
  • f returns beta
  • a seed of beta represents the empty-list case
  • finite-list expansion: f(first, f(second, ... seed))

4

Reduce takes the combining function, list and seed

  • type: (alpha # beta -> beta) # list(alpha) # beta -> beta
  • empty list -> seed
  • nonempty -> f(head, Reduce(f,tail,seed))

examples:

  • (+) with seed 0 sums [1,2,3,4] to 10
  • (*) with seed 1 multiplies it to 24

5

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
Keep the tail suspended; unfold only enough cells to satisfy the consumer.
A finite demand can use an infinite structure. Open full size - Editable SVG
Book examples (2 files) - 11.5.12: Infinite data structures: examples
Book exampleBook example: pascal_t.hopIn catalog
pascal_t.hopHope / 50 lines
#!/usr/local/bin/hopeless -f

dec NextLineRest : list(num) -> list(num);
--- NextLineRest([k]) <= [k];
--- NextLineRest(a::b::ls) <= (a+b) :: NextLineRest(b::ls);

dec NextLine : list(num) -> list(num);
--- NextLine(ls) <= 1::NextLineRest(ls);

dec PascalsTriangleBuild : list(num) -> list(list(num));
--- PascalsTriangleBuild(ls) <= ls::PascalsTriangleBuild(NextLine(ls));

dec PascalsTriangle : list(list(num));
--- PascalsTriangle <= PascalsTriangleBuild([1]);

dec Nth : list alpha # num -> alpha;
--- Nth (x :: ls, n) <= if n = 0 then x else Nth (ls, n - 1);

dec Cnk : num # num -> num;
--- Cnk(n, k) <= Nth(Nth(PascalsTriangle, n), k);

! -------------------------------------------------------------------------


dec NumList2Str : list(num) -> list(char);
--- NumList2Str([]) <= [];
--- NumList2Str(n :: rest) <= num2str n <> " " <> NumList2Str(rest);

! dec LineByLine : list(char) # list(list(num)) -> list(char);
! --- LineByLine([], _) <= [];
! --- LineByLine(ch :: inp, h :: t) <=
!         if ch = '\n' then
!                 NumList2Str h <> LineByLine(inp, t)
!         else
!                 LineByLine(inp, h :: t);

dec LineByLine : list(char) # list(list(num)) -> list(char);
--- LineByLine([], _) <= [];
--- LineByLine('\n' :: inp, h :: t) <=
        NumList2Str h <> LineByLine(inp, t);
--- LineByLine(_ :: inp, h :: t) <=
        LineByLine(inp, h :: t);

dec main : list(list(char)) # list(char) -> list(char);
--- main([], inp)     <= LineByLine("\n" <> inp, PascalsTriangle);
--- main(n::[], _)    <= NumList2Str(Nth(PascalsTriangle, str2num n));
--- main(n::k::[], _) <= num2str(Cnk(str2num n, str2num k));
--- main(lst, _)      <= "Too many arguments, sorry";

write main(argv, input) <> "\n";
Book exampleBook example: sieve.hopIn catalog
sieve.hopHope / 17 lines
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
f(x,y) = 10*x + y becomes a function that accepts x, then returns a function awaiting y.
Currying replaces a tuple input with a returned function. Open full size - Editable SVG

11.5.15 The fixed-point combinator

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
For a list sum, the transformer receives the recursive operation instead of calling itself by name.
A fixed point ties a recursive function back to its body. Open full size - Editable SVG
Book example (1 file) - 11.5.15: The fixed-point combinator
Book exampleBook example: y.hopIn catalog
y.hopHope / 50 lines
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;

Previous: C++ Programming Reading map Next: Scripting and Execution Strategies

Comments

Leave a comment Sign in All comments