Programming Paradigms

Reading map

Previous: Inside the Kernel Reading map Next: C++ Programming

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

Programming paradigms shape how a problem is understood, from changing machine state to composing functions or exchanging object messages. Recursion, callbacks, and explicit states show how several models can coexist within one program.

Chapter Map

9.1 The word paradigm

Abstraction shifts attention from machine operations toward the problem being solved. Learning alternative models, including functional and object-oriented approaches, broadens the solutions a programmer can recognize without removing practical performance constraints.

Detailed notes - 9.1: The word paradigm

1

first two volumes approached programming from the machine upward

  • Pascal fundamentals, assembly, C, and operating-system services
  • this volume turns to other ways of understanding programs

2

"high level" historically meant above assembly

  • book treats C as comparatively low level: representation and machine behavior remain important to the programmer
  • assembly can supply target-specific operations missing from C
  • system calls define the OS-service boundary for ordinary processes
  • C's usefulness here does not make it the only possible systems language

3

Pascal also exposes the stored-program machine model

  • variables occupy memory; pointers identify memory locations
  • assignment changes stored state
  • being above assembly does not remove those assumptions

4

low-level programming uses knowledge of the machine deliberately

  • improve efficiency or expose capabilities
  • systems software serves other software and computer operation
  • application software directly addresses the user's external problem

5

systems software often needs machine-level knowledge

  • its performance can affect many applications at once
  • kernel efficiency is an especially broad example

6

application development has additional tradeoffs

  • development effort and delivery time may outweigh small runtime costs
  • acceptable performance still depends on the particular application

7

abstraction can shift attention from machine mechanics to the problem

  • seek a simpler, shorter, or clearer expression of the desired behavior
  • alternative mental models become possible

8

volume examines paradigms beyond familiar imperative programming

  • object-oriented approaches
  • models where variables are not mutable memory cells
  • programs without assignments or explicit loops

9

several paradigms have already appeared in systems work

  • recursion: a local way of structuring an algorithm
  • event-driven execution and explicit states: whole-program organization
  • parallel programming: multiple interacting control flows
  • paradigms are not restricted to application programming

10

language features can influence how a programmer frames a problem

  • even Pascal and C encourage noticeably different habits
  • systems constraints restrict choices; other tasks may allow more freedom

11

learning several models develops flexibility

  • a paradigm can improve understanding even if never used directly at work

9.1.1 Terminological difficulties

A paradigm can concern an entire program or a small technique, so lists of styles do not establish a precise definition. Event loops, text interfaces, shared data, and recursion illustrate the term's varied scope.

Detailed notes - 9.1.1: Terminological difficulties

1

previously introduced styles include imperative, functional, declarative, and object-oriented programming

2

Unix design supplies further examples

  • "everything is a byte stream" shapes interfaces
  • "one program, one task" concerns system composition more broadly

3

preferring text is a representation paradigm

  • inspect, edit, and combine data with general text tools
  • exceptions include machine code, compressed/encrypted data, and media whose textual encoding would not make it directly understandable

4

an event-driven program has a repeating event loop

  • obtain an event
  • perform the corresponding response
  • organize actions around available events rather than one dialogue

5

parallel execution and shared-data programming are distinct ideas

  • parallel processes can communicate by messages instead of shared memory
  • independent applications can share persistent files
  • either technique introduces its own reasoning requirements

6

recursion is another paradigm, at a different scale

  • examples suggest different ways of thinking about the same problem
  • the term needs more explanation than a list of programming techniques

7

authors disagree on what belongs in the category

  • Floyd includes structured programming; some other accounts do not
  • definitions vary and can presuppose the understanding they should explain

8

ask why the term is needed and what recognizing it helps us do

  • historical purpose can clarify an otherwise vague definition

9.1.2 Paradigms outside programming

A paradigm is an approach to understanding the same subject, illustrated through geometry and skiing. Programming differs from an exclusive scientific paradigm shift: several models can coexist, and experience helps choose among them.

Detailed notes - 9.1.2: Paradigms outside programming

1

Greek origin suggests example/model

  • Kuhn used the term for established frameworks of scientific inquiry
  • paradigm shifts replace a way of explaining the same phenomena
  • old and new frameworks may coexist during a transition

2

social and political discussion also uses "paradigm shift"

  • the phrase alone does not explain which assumptions are changing

3

common theme: different ways of interpreting one phenomenon

  • distinguish the phenomenon from a person's model of it

4

working meaning used by this book:

  • paradigm = an approach to understanding/modeling a subject
  • following examples clarify this before returning to programs

5

geometry can be understood visually or through formal statements

  • drawn spots/lines are illustrations, not ideal mathematical objects
  • axioms and reasoning do not require a particular drawing
  • both approaches concern the same underlying geometry

6

individual mental pictures differ even within the visual approach

  • author's image of brown lines came from a school textbook
  • learning pointers can likewise involve distinct personal models

7

learning a difficult subject involves forming a usable mental model

  • good teaching helps build that model rather than merely presenting facts

8

skiing is offered as an example outside mathematics and programming

  • physical activity also depends on how the participant interprets it

9

author contrasts the movement and attention of novices and practiced skiers

  • focus is on the model behind an observable difference

10

example's practical problem: retain control of speed while descending

  • uncontrolled acceleration makes stable movement difficult

11

turns can be viewed as the whole trajectory or as means toward a destination

  • novice model: follow the immediate zigzag
  • experienced model: aim along an overall route, with turns serving it
  • same physical descent, different organization of attention

12

explaining the purpose of an action helps change the model behind it

  • author distinguishes understanding an instruction from imitating it

13

Floyd applied the paradigm idea to programming

  • different programming paradigms can coexist and combine
  • individual development involves expanding one's repertoire

14

there is no universal recipe for choosing the best paradigm for every task

  • available models, constraints, and programmer experience affect the choice
  • flexible thinking increases the set of solutions one can consider

9.1.3 Main programming styles

Imperative programs change state; functional programs compose computations; logic programs search for satisfying relations; object-oriented designs organize behavior behind object interfaces. These broad styles overlap, while ADTs emphasize hidden representations and controlled value operations.

The same styles side by side. A C program written functionally: make_output describes the whole output as a list, built by nested calls without assigning anything; only main performs actions:

struct str_item *make_output(int i, int argc, char **argv)
{
    return i >= argc ? NULL :
        mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}
Show the complete program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct str_item {
    char *str;
    struct str_item *next;
};

struct str_item *mkitem(const char *s, struct str_item *tail)
{
    struct str_item *p = malloc(sizeof(*p));
    p->str = malloc(strlen(s) + 1);
    strcpy(p->str, s);
    p->next = tail;
    return p;
}

struct str_item *make_output(int i, int argc, char **argv)
{
    return i >= argc ? NULL :
        mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}

struct str_item *main_func(int argc, char **argv)
{
    return make_output(0, argc, argv);
}

int main(int argc, char **argv)
{
    struct str_item *p, *tmp;
    p = main_func(argc, argv);
    for (; p; p = tmp) {
        tmp = p->next;
        fputs(p->str, stdout);
        free(p->str);
        free(p);
    }
    return 0;
}
$ ./functional one two
./functional
one
two

Logic programming states facts and rules and lets the system search:

parent(mary, ann).
parent(mary, john).
parent(george, john).

male(george).
male(john).

female(mary).
female(ann).

father(X, Y) :-
    parent(X, Y),
    male(X).

mother(X, Y) :-
    parent(X, Y),
    female(X).

brother(X, Y) :-
    parent(T, X),
    parent(T, Y),
    male(X).
?- brother(X, ann).
?- father(F, john).
?- brother(john, john).

The first query finds X = john, the second F = george. The third also succeeds: nothing in the rule says that X and Y are different people, so it needs an extra condition X \= Y.

Haskell, a purely functional language, describes the whole output as a function of the whole input; interact connects that function to the streams:

main :: IO ()
main = interact numberLines

numberLines :: String -> String
numberLines input =
    unlines $
    zipWith addNumber [1..] (lines input)

addNumber :: Integer -> String -> String
addNumber n line =
    show n ++ ": " ++ line
$ printf 'first\nsecond\n' | ./number
1: first
2: second
Detailed notes - 9.1.3: Main programming styles

1

imperative program acts within an execution environment

  • variables, streams, other processes, users, and controlled devices
  • environment includes anything affecting or affected by the program

2

imperative reasoning centers on state that changes over time

  • this is one model of computation, not a requirement of every algorithm
  • a mathematical transformation can be described without mutable cells

3

program instructions tell an executor which actions to perform

  • executor may be a CPU or interpreter
  • imperative means command-oriented

4

assignment is a characteristic imperative action

  • replace the value in a variable
  • previous value is lost unless saved elsewhere
  • other actions include I/O, signaling, and connection management

5

assignment requires a mental model of changing variable values

  • author describes it as a difficult early teaching barrier
  • his generalizations about innate aptitude reflect his experience, not a demonstrated rule about who can learn programming

6

tracing loops also requires imagining execution over time

  • author links difficulties with loops to that same mental-model issue

7

book calls this mutable-memory model von Neumann programming

  • connects variable updates to the stored-program machine
  • cites Backus's use of the terminology

8

historical von Neumann programming differed in implementation details

  • early machines sometimes modified instruction operands to index data
  • ordinary modern code is commonly protected from writes
  • the continuing conceptual feature is mutable state and assignment

9

procedural and imperative are not identical

  • imperative instructions do not inherently require isolated subprograms

10

historical line-numbered BASIC combined editing and execution

  • entering a numbered line inserted/replaced that program line
  • interactive commands executed directly
  • cassette-based machines made separate editor/compiler workflows costly

11

BASIC line numbers also served as jump destinations

  • GOTO supplied control transfers
  • numbering by tens left room for later insertions
  • renumbering tools also updated references to those numbers

12

GOSUB / RETURN supplied limited call-like control flow

  • described BASIC lacked local variables and formal parameter isolation
  • global variables carried information between fragments

13

procedural programming decomposes a problem into isolated subprograms

  • caller relies on the interface, not the implementation
  • implementing a helper should not require knowledge of each caller
  • one call can stand for a complex subtask

14

parameters and local state support that separation

  • separate call frames allow independent active invocations
  • support recursive use
  • stack frames alone do not make shared global state safely reentrant

15

assembly programmers can impose procedural organization manually

  • calls, stack frames, conventions, and local naming require deliberate work
  • language support and programmer discipline are different sources of structure

16

procedural programming is an important form of imperative organization

  • the two terms should not be used as interchangeable definitions

17

command scripting is another imperative style

  • examples organize commands and data through textual representations
  • named values need not expose addressable machine memory to the programmer
  • source emphasizes interpreted execution; implementations may add compilation

18

pure functional programming avoids destructive state updates

  • compute results instead of changing an existing environment in place
  • "destructive" and "modifying" describe the same state-change concern here

19

functional variables can denote immutable bindings

  • parameters bind to supplied arguments
  • local names denote computed values
  • establishing a binding is distinct from overwriting an earlier value

20

functions are the main composition units

  • first-class functions can be stored, passed, and returned
  • functional languages commonly create function values at runtime

21

function syntax alone does not make a program functional

  • C also has functions and function pointers
  • ordinary C functions often perform effects instead of pure mappings
  • pure result depends only on inputs, without other observable effects
  • replacing a pure computation with its value preserves its meaning

22

a functional subset can be imposed on an imperative language

  • avoid assignments, increments, and effectful helper calls in the core
  • theoretical computability assumes an idealized resource model
  • practical expressiveness and convenience still differ from a functional language

23

without updates, mutable global variables and ordinary state-changing loops disappear

  • recursion can express repeated computation instead
  • string search: empty -> NULL; matching head -> current address
  • otherwise recurse on s+1
  • function decomposition replaces the loop's changing pointer

24

recursive repetition has a resource cost unless tail calls can reuse frames

  • return g(y) leaves no work for the current invocation after g completes
  • frame can sometimes be replaced rather than retained
  • C permits some such optimizations but does not guarantee them

25

computability models abstract away finite memory limits

  • unbounded tape and unbounded recursion are idealizations
  • do not confuse this theoretical equivalence with practical stack capacity

26

I/O changes the program's observable environment

  • reading consumes external input; writing affects output and other participants
  • a pure computational core still needs some account of interaction

27

languages combine pure computations with effects in different ways

  • Lisp/Scheme also expose mutation and ordinary I/O
  • lazy sequences can represent incrementally supplied input/output
  • source's Hope example emits elements of an output list as needed
  • lazy evaluation is one useful technique, not a universal prerequisite for pure effect models

28

Haskell's IO organizes effectful actions as values composed by pure code

  • the runtime executes the resulting action
  • this is more structured than treating every expression as an arbitrary I/O action

29

monad terminology can be a teaching obstacle

  • a mathematical definition alone may not explain its programming purpose

30

seminar anecdote: several accounts of monads emphasized different intuitions

  • illustrates the difficulty of teaching a new mental model

31

book does not develop Haskell or monad programming further

32

restricted C example takes its inputs through command-line arguments

  • exit status alone is too small a channel for arbitrary result data
  • eliminating normal output therefore creates an interface problem

33

one option allows I/O while keeping other computations free of effects

  • a pragmatic mixture rather than a completely pure program

34

illustration separates a functional core from effectful wrappers

  • main_func receives argc/argv and returns a list of output strings
  • mkitem allocates and initializes a fresh list node
  • main traverses the result and performs fputs calls
  • allocation, failure handling, output, and cleanup remain boundary concerns
  • this simple batch model does not provide general interactive timing

35

input/output histories can be encoded as data transformations

  • environment reactions and timing add concerns beyond a fixed batch input

36

interactive input may not exist until after the program produces output

  • external participant can delay, react, or make independent choices
  • program and environment can each wait for the other -> deadlock
  • protocol ordering is therefore part of the practical problem

37

logic programming describes facts and inference rules

  • execution seeks a proof/solution of a query

38

Prolog is the main logic-programming example

  • can also be understood operationally as searching alternatives
  • declarative and procedural readings expose different aspects

39

logic programming requires an inference/search mechanism

  • a general-purpose language can implement or host such a mechanism
  • simply avoiding mutation does not supply a logic solver

40

family example uses parent, male, and female facts

  • queries such as parent(X, ann) ask for satisfying bindings
  • father/mother rules combine parenthood with another predicate
  • brother rule combines shared parent and male status
  • example finds John as Ann's brother
  • a complete sibling relation must also exclude a person being their own sibling

41

more facts and rules express richer relational queries

  • combine age, education, language, occupation, and family information

42

declarative view specifies properties of a desired result

  • solver chooses how to search for a satisfying object
  • distinguish describing what is wanted from prescribing each search step

43

declarative programming is broader than logic programming

  • SQL is another declarative interface, based on relational queries

44

relations connect logic predicates with database tables

  • a fact resembles a tuple/row
  • Prolog's dynamic database can be modified through effectful operations

45

logic languages can serve as database-query tools

  • Prolog and Datalog supply examples
  • author's criticism of SQL dominance is a design viewpoint

46

Prolog also includes mechanisms that complicate a purely logical reading

  • I/O and dynamic database updates have effects
  • arithmetic evaluation, cut, and negation have operational conditions
  • variables denote unknowns/bindings, not ordinary assignment targets
  • recursion remains a major structuring tool

47

some Prolog programs require reasoning about the solver's search order

  • pure subsets and languages such as Datalog support a more restricted, declarative interpretation

48

object-oriented programming is often explained using three terms

  • encapsulation, inheritance, polymorphism
  • their mechanisms and purpose matter more than repeating the terminology

49

modularity helps control the complexity perceived by a programmer

  • hiding private names reduces how much context must be held at once

50

encapsulation hides implementation behind an interface

  • local variables and module-private names already provide examples

51

object model groups behavior behind individual object interfaces

  • client sends a request and receives a response
  • implementation may change internal state or communicate with other objects
  • clients rely on the contract rather than internal representation

52

object-level encapsulation can reduce visible complexity within a module

  • builds on, rather than invents, information hiding

53

class describes a family of objects

  • instances follow that description
  • inheritance derives a related class from an existing one

54

several classes may support a common interface

  • clients can use that shared set of operations

55

polymorphism means that similar syntax can have type-dependent behavior

  • + for different numeric types or strings
  • array and pointer expressions can also select different mechanisms
  • these examples are not uniquely object-oriented

56

operator overloading and subtype polymorphism are distinct facilities

  • derived objects can be used through a suitable base interface
  • virtual dispatch can select derived behavior
  • source contrasts class-based OOP with object-based facilities lacking inheritance

57

abstract data type: representation hidden behind permitted operations

  • FILE* is an interface example: clients use functions, not private layout
  • representation-independent operations help distinguish abstraction from raw storage

58

ADTs and object-oriented interfaces both hide implementation

  • shared encapsulation does not make the two models identical
  • author emphasizes message-oriented object reasoning as a further shift

59

book contrasts value copying with independent object identity

  • an ADT may define value assignment/copying
  • copying a value is not the same as sending an object a request
  • exact assignment semantics depend on the language/model

60

object-oriented and imperative features often coexist in one language

  • author argues that this popularity should not define OOP itself
  • his "pure OOP" classification is one conceptual interpretation

61

many object-oriented languages still use assignment and changing state

  • state is shared ground with imperative programming
  • organization of access to it differs

62

major style labels do not determine every aspect of a program

  • each leaves room for local models, strategies, and individual reasoning

63

smaller paradigms can coexist inside a broader one

  • callbacks, states, loops, recursion, and bindings shape thought locally
  • aim of this volume: learn to switch models deliberately
Tests & experiments (5 files) - 9.1.3: Main programming styles
Section testparadigms (09-01-03)In catalog
09-01-03-script.shShell / 3 lines
x=42
name="x"
echo "${!name}"
MakefileMake / 12 lines
PROGRAMS = functional

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
family.plProlog / 22 lines
parent(mary, ann).
parent(mary, john).
parent(george, john).

male(george).
male(john).

female(mary).
female(ann).

father(X, Y) :-
    parent(X, Y),
    male(X).

mother(X, Y) :-
    parent(X, Y),
    female(X).

brother(X, Y) :-
    parent(T, X),
    parent(T, Y),
    male(X).
functional.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct str_item {
    char *str;
    struct str_item *next;
};

struct str_item *mkitem(const char *s, struct str_item *tail)
{
    struct str_item *p = malloc(sizeof(*p));
    p->str = malloc(strlen(s) + 1);
    strcpy(p->str, s);
    p->next = tail;
    return p;
}

struct str_item *make_output(int i, int argc, char **argv)
{
    return i >= argc ? NULL :
        mkitem(argv[i], mkitem("\n", make_output(i + 1, argc, argv)));
}

struct str_item *main_func(int argc, char **argv)
{
    return make_output(0, argc, argv);
}

int main(int argc, char **argv)
{
    struct str_item *p, *tmp;
    p = main_func(argc, argv);
    for (; p; p = tmp) {
        tmp = p->next;
        fputs(p->str, stdout);
        free(p->str);
        free(p);
    }
    return 0;
}
strchar.cC / 37 lines
#include <stdio.h>

const char *strchar1(const char *s, char c)
{
    const char *p;
    for (p = s; *p; p++)
        if (*p == c)
            return p;
    return NULL;
}

const char *strchar2(const char *s, char c)
{
    if (!*s)
        return NULL;
    if (*s == c)
        return s;
    return strchar2(s + 1, c);
}

const char *strchar3(const char *s, char c)
{
    return !*s ? NULL : *s == c ? s : strchar3(s + 1, c);
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <str> <char>\n", argv[0]);
        return 1;
    }

    const char *res = strchar3(argv[1], argv[2][0]);
    printf("%s\n", res);

    return 0;
}

9.2 Recursion as a paradigm

Recursion is both a calling technique and a way to understand a problem through smaller instances. Language support affects its convenience, but writing a self-call does not itself establish recursive thinking.

Detailed notes - 9.2: Recursion as a paradigm

1

languages differ in how naturally they support recursive solutions

  • some functional/logic styles rely on them extensively
  • Pascal/C allow a choice among several formulations
  • low-level assembly requires explicit calling/frame conventions
  • historical dialects lacking local call state make recursion difficult

2

study recursion as a model of thought, not only a self-calling technique

9.2.1 Tree traversal example

Recursive inorder traversal leaves unfinished work in call frames, while an iterative version records nodes and continuation stages in an explicit stack. Both preserve equivalent information; the main difference is how the programmer describes that work.

Detailed notes - 9.2.1: Tree traversal example

1

recursive inorder traversal:

  • empty tree -> return
  • traverse left subtree, print current value, traverse right subtree
  • node stores val plus left/right links

2

iterative traversal explicitly remembers the path back to ancestor nodes

  • linked stack entries hold node pointers and processing state
  • push a child when descending; pop when its subtree is finished
  • handle an empty input tree and allocation failure in complete code

3

three states for a saved node:

  • start: left subtree, value, and right subtree still need processing
  • left_visited: print value and process right subtree
  • completed: remove this stack entry and resume its parent
  • begin with a start entry for the root
  • before descending left, mark the parent left_visited

4

left subtree completed -> print current value

  • mark current node completed before descending right
  • absent right child needs no descent

5

completed node -> pop its traversal frame

  • popping the root's frame empties the stack and ends the loop

6

switch fallthrough skips redundant loop iterations for absent children

  • omitting the optimization can make the state transitions easier to follow
  • behavior remains the same; performance difference is implementation-specific

7

explicit path list is a stack

  • most recently entered node is processed first
  • each entry remembers node address and continuation stage

8

recursive calls preserve equivalent information implicitly

  • parameter identifies the node
  • instruction position identifies current work
  • return address records where parent processing resumes

9

both versions save a node and unfinished work for each active subtree

  • stack entry lifetime corresponds to entering/leaving that subtree
  • machine-level operations are closely related

10

representation of the explicit stack affects cost

  • allocating a linked node per traversal step adds overhead
  • an expandable array can reduce it
  • assembly can even use the hardware stack explicitly

11

main contrast is the programmer's description of the work

  • short recursive decomposition versus explicit continuation bookkeeping
  • paradigm shapes how a person understands the algorithm
In-order traversal: finish the left subtree, visit the node, then finish the right subtree.
Recursion remembers the route through a tree. Open full size - Editable SVG
Tests & experiments (11 files) - 9.2.1: Tree traversal example
Section testtree-00 (09-02-01)In catalog
09-02-01-tree-00.asmAssembly / 183 lines
%include "calls.inc"

%assign stack_len        1024
%assign num_len          12      ; sign + 10 decimal digits + space

%assign start            0
%assign left_visited     1
%assign completed        2

%assign node_val         0
%assign node_left        4
%assign node_right       8
%assign node_size        12

%assign stack_p          0
%assign stack_st         4
%assign stack_size       8

; Inline traversal records on the hardware stack.
; Use stable operands, not ESP-relative operands.
%macro stack_push 3              ; (size_operand, node_pointer, state)
        inc     dword %1
        push    dword %3
        push    dword %2
%endmacro

%macro stack_pop 1               ; (size_operand)
        dec     dword %1
        add     esp, stack_size
%endmacro

global _start
extern sint2str

section .data

new_line        db 10

section .text

print_int:
        ; (val: 8)
        ; sint2str -> append a space -> write to stdout.
        pbegin  num_len, ebx, esi, edi
        lea     edi, [ebp-num_len]       ; local conversion buffer
        pcall   sint2str, [ebp+8], edi

        mov     byte [edi+eax], ' '
        inc     eax
        mov     esi, eax                ; length including the space
.write:
        scall   4, 1, edi, esi
        cmp     eax, -4                 ; -EINTR: retry
        je      .write
        test    eax, eax
        jle     .error
        add     edi, eax
        sub     esi, eax
        jne     .write                  ; finish any partial write
        pend    ebx, esi, edi
.error:
        scall   1, 3

tree_push:
        ; (p: 8, nodes: 12, nodes_used: 16, val: 20)
        pbegin  0
        mov     eax, [ebp+16]
        mov     edx, [eax]
        imul    edx, node_size
        add     edx, [ebp+12]            ; tmp = &nodes[*nodes_used]
        inc     dword [eax]             ; (*nodes_used)++

        mov     ecx, [ebp+20]
        mov     [edx+node_val], ecx
        mov     dword [edx+node_left], 0
        mov     dword [edx+node_right], 0
        mov     eax, [ebp+8]
        mov     [eax], edx              ; *p = tmp
        pend

tree_insert:
        ; (p: 8, nodes: 12, nodes_used: 16, val: 20)
        pbegin  0
        mov     eax, [ebp+8]
        mov     eax, [eax]
        test    eax, eax
        je      .new_node

        mov     edx, [ebp+20]
        cmp     edx, [eax+node_val]
        jl      .left
        jg      .right
        jmp     .end
.new_node:
        pcall   tree_push, [ebp+8], [ebp+12], [ebp+16], [ebp+20]
        jmp     .end
.left:
        lea     eax, [eax+node_left]
        pcall   tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
        jmp     .end
.right:
        lea     eax, [eax+node_right]
        pcall   tree_insert, eax, [ebp+12], [ebp+16], [ebp+20]
.end:
        pend

tree_print1:
        ; (p: 8)
        pbegin  0, ebx
        mov     ebx, [ebp+8]
        test    ebx, ebx
        jz      .end

        pcall   tree_print1, [ebx+node_left]
        pcall   print_int, [ebx+node_val]
        pcall   tree_print1, [ebx+node_right]
.end:
        pend    ebx

tree_print:
        ; (p: 8)
        ; [ebp-4] = size
        ; ebx = s, pointing to the current traversal record
        pbegin  4, ebx
        mov     dword [ebp-4], 0
        mov     eax, [ebp+8]
        test    eax, eax
        je      .end

        stack_push [ebp-4], eax, start
.lp:
        cmp     dword [ebp-4], 0
        je      .end
        mov     ebx, esp
        mov     eax, [ebx+stack_st]
        cmp     eax, start
        je      .start
        cmp     eax, left_visited
        je      .left_visited
        cmp     eax, completed
        je      .completed
        jmp     .lp
.start:
        mov     dword [ebx+stack_st], left_visited
        mov     eax, [ebx+stack_p]
        mov     eax, [eax+node_left]
        test    eax, eax
        je      .lp
        stack_push [ebp-4], eax, start
        jmp     .lp
.left_visited:
        mov     eax, [ebx+stack_p]
        pcall   print_int, [eax+node_val]

        mov     dword [ebx+stack_st], completed
        mov     eax, [ebx+stack_p]
        mov     eax, [eax+node_right]
        test    eax, eax
        je      .lp
        stack_push [ebp-4], eax, start
        jmp     .lp
.completed:
        stack_pop [ebp-4]
        jmp     .lp
.end:
        pend    ebx

_start:
        ; [ebp-4] = p, [ebp-8] = nodes_used
        ; [ebp-(8+stack_len*node_size)] = nodes[0]
        pbegin  8+stack_len*node_size, ebx, esi, edi
        mov     dword [ebp-4], 0
        mov     dword [ebp-8], 0
        lea     ebx, [ebp-4]
        lea     esi, [ebp-(8+stack_len*node_size)]
        lea     edi, [ebp-8]

        pcall   tree_insert, ebx, esi, edi, 1
        pcall   tree_insert, ebx, esi, edi, 3
        pcall   tree_insert, ebx, esi, edi, 2
        pcall   tree_print, [ebp-4]
        scall   4, 1, new_line, 1
        scall   1, 0
09-02-01-tree-00.cC / 101 lines
#include <stdio.h>
#include <stdlib.h>

enum state {
    start,
    left_visited,
    completed
};

struct node {
    int val;
    struct node *left, *right;
};

struct stack {
    const struct node *p;
    enum state st;
    struct stack *next;
};

void stack_push(struct stack **s, const struct node *p, const enum state st)
{
    struct stack *tmp = malloc(sizeof(*tmp));
    tmp->p = p;
    tmp->st = st;
    tmp->next = *s;
    *s = tmp;
}

void stack_pop(struct stack **s)
{
    struct stack *tmp = *s;
    *s = (*s)->next;
    free(tmp);
}

void tree_push(struct node **p, int val)
{
    struct node *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, int val)
{
    if (!*p)
        tree_push(p, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, val);
}

void tree_print1(const struct node *p)
{
    if (!p)
        return;
    tree_print1(p->left);
    printf("%d ", p->val);
    tree_print1(p->right);
}

void tree_print(const struct node *p)
{
    struct stack *s;
    s = NULL;
    stack_push(&s, p, start);
    while (s)
        switch (s->st) {
            case start:
                s->st = left_visited;
                if (s->p->left)
                    stack_push(&s, s->p->left, start);
                break;
            case left_visited:
                printf("%d ", s->p->val);
                s->st = completed;
                if (s->p->right)
                    stack_push(&s, s->p->right, start);
                break;
            case completed:
                stack_pop(&s);
        }
}

int main()
{
    struct node *p;

    p = NULL;
    tree_insert(&p, 1);
    tree_insert(&p, 3);
    tree_insert(&p, 2);
    tree_insert(&p, 3);
    tree_print(p);
    printf("\n");

    return 0;
}
09-02-01-tree-01.cC / 102 lines
#include <stdio.h>

enum { stack_len = 1024 };

enum state {
    start,
    left_visited,
    completed
};

struct node {
    int val;
    struct node *left, *right;
};

struct stack {
    const struct node *p;
    enum state st;
};

void stack_push(struct stack *s, int *size,
                const struct node *p, const enum state st)
{
    struct stack *tmp = &s[*size];
    (*size)++;
    tmp->p = p;
    tmp->st = st;
}

void stack_pop(int *size)
{
    (*size)--;
}

void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    struct node *tmp = &nodes[*nodes_used];
    (*nodes_used)++;
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    if (!*p)
        tree_push(p, nodes, nodes_used, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, nodes, nodes_used, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, nodes, nodes_used, val);
}

void tree_print1(const struct node *p)
{
    if (!p)
        return;
    tree_print1(p->left);
    printf("%d ", p->val);
    tree_print1(p->right);
}

void tree_print(const struct node *p)
{
    struct stack backpath[stack_len], *s;
    int size = 0;
    stack_push(backpath, &size, p, start);
    while (size) {
        s = &backpath[size - 1];
        switch (s->st) {
            case start:
                s->st = left_visited;
                if (s->p->left)
                    stack_push(backpath, &size, s->p->left, start);
                break;
            case left_visited:
                printf("%d ", s->p->val);
                s->st = completed;
                if (s->p->right)
                    stack_push(backpath, &size, s->p->right, start);
                break;
            case completed:
                stack_pop(&size);
        }
    }
}

int main()
{
    struct node *p, nodes[stack_len];
    int nodes_used = 0;

    p = NULL;
    tree_insert(&p, nodes, &nodes_used, 1);
    tree_insert(&p, nodes, &nodes_used, 3);
    tree_insert(&p, nodes, &nodes_used, 2);
    tree_print(p);
    printf("\n");

    return 0;
}
MakefileMake / 29 lines
PROGRAMS = 09-02-01-tree-01
ASSEMBLY = 09-02-01-tree-00

ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)

CC = gcc
CFLAGS = -g -Wall

NASM = nasm
NASMFLAGS = -f elf32 -g

LD = ld
ASLDFLAGS = -m elf_i386

all: $(PROGRAMS) $(ASSEMBLY)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

%.o: %.asm
    $(NASM) $(NASMFLAGS) $< -o $@

$(ASSEMBLY): %: %.o $(AOBJMODULES)
    $(LD) $(ASLDFLAGS) $^ -o $@

clean:
    $(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
calls.incAssembly / 67 lines
%macro pcall 1-*
; call subroutines < (name, param1, param2, param3)
  %rep %0 - 1
    %rotate -1
    push    dword %1
  %endrep
  %rotate -1
    call    %1
    add     esp, (%0 - 1)*4
%endmacro

%macro scall 1-4
; system call
;   < (interrupt number, param1, param2, param3)
  %if %0 > 1
    push    ebx             ; it can only spoil eax, ecx, edx
  %endif

  %rep %0
    %rotate -1
    push    dword %1        ; push in reverse order
  %endrep
    pop     eax
  %if %0 > 1
    pop     ebx
    %if %0 > 2
    pop     ecx
      %if %0 > 3
    pop     edx
      %endif
    %endif
  %endif
    int     80h

    cmp     eax, 0xfffff000
    jb %%ok
    mov     ecx, -1
    jmp short %%end
%%ok:
    xor     ecx, ecx
%%end:
  %if %0 > 1
    pop     ebx
  %endif
%endmacro

%macro pbegin 1-4
; procedure header < (sub, reg1, reg2, reg3)
    push    ebp
    mov     ebp, esp
    sub     esp, %1
  %rep %0-1
    %rotate 1
    push    %1
  %endrep
%endmacro

%macro pend 0-3
; procedure tail < (reg1, reg2, reg3)
  %rep %0
    %rotate -1
    pop     %1
  %endrep
    mov     esp, ebp
    pop     ebp
    ret
%endmacro
sint2str.asmAssembly / 59 lines
global sint2str

section .text

sint2str:       ; (number: 8, result: 12) -> string length in eax
        push    ebp
        mov     ebp, esp
        sub     esp, 4
        push    ebx
        push    esi
        push    edi
        mov     esi, [ebp+8]            ; number to convert
        mov     edi, [ebp+12]           ; result buffer
        mov     ebx, 10
        mov     dword [ebp-4], 0        ; negative?

        cmp     esi, 0
        jge     .not_negative           ; signed comparison
        not     esi
        inc     esi                    ; unsigned magnitude
        mov     dword [ebp-4], 1
.not_negative:
        mov     eax, esi
        xor     ecx, ecx
.lp:
        xor     edx, edx
        div     ebx
        add     edx, '0'
        mov     [edi+ecx], dl
        inc     ecx
        cmp     eax, 0
        jne     .lp

        cmp     dword [ebp-4], 1
        jne     .not_negative2
        mov     byte [edi+ecx], '-'
        inc     ecx
.not_negative2:
        push    ecx                    ; save string length

        dec     ecx
        xor     ebx, ebx
.lp2:
        mov     al, [edi+ebx]           ; swap one byte at each end
        mov     dl, [edi+ecx]
        mov     [edi+ebx], dl
        mov     [edi+ecx], al
        inc     ebx
        dec     ecx
        cmp     ebx, ecx
        jl      .lp2

        pop     eax                    ; string length, including sign
        pop     edi
        pop     esi
        pop     ebx
        mov     esp, ebp
        pop     ebp
        ret
Section testtree-01 (09-02-01)In catalog
MakefileMake / 31 lines
PROGRAMS = tree-01
ASSEMBLY = tree-00

ASRCMODULES = sint2str.asm
AOBJMODULES = $(ASRCMODULES:.asm=.o)
AOBJECTS = $(ASSEMBLY:=.o) $(AOBJMODULES)

CC = gcc
CFLAGS = -g -Wall -O0

NASM = nasm
NASMFLAGS = -f elf64 -g

LD = ld
ASLDFLAGS = -m elf_x86_64 -e _start

.PHONY: all clean

all: $(PROGRAMS) $(ASSEMBLY)

$(PROGRAMS): %: %.c
    $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $< $(LDLIBS) -o $@

%.o: %.asm calls.inc
    $(NASM) $(NASMFLAGS) $< -o $@

$(ASSEMBLY): %: %.o $(AOBJMODULES)
    $(LD) $(ASLDFLAGS) $^ -o $@

clean:
    $(RM) $(AOBJECTS) $(PROGRAMS) $(ASSEMBLY)
calls.incAssembly / 81 lines
%ifndef CALLS_INC
%define CALLS_INC

%macro pbegin 1-*
; procedure header < (sub, reg1, reg2, reg3, ...)
; Keep rsp divisible by 16 before calling another function.
    push    rbp
    mov rbp, rsp
    sub rsp, %1
  %rep %0 - 1
    %rotate 1
    push    %1
  %endrep
%endmacro

%macro pend 0-*
; procedure tail < (reg1, reg2, reg3, ...)
  %rep %0
    %rotate -1
    pop %1
  %endrep
    mov rsp, rbp
    pop rbp
    ret
%endmacro

%macro pcall 1-7
; System V call < (name, param1, ..., param6)
; Integer/pointer arguments only. Use 64-bit registers or qword memory.
; Capture operands before changing argument registers; no RSP operands.
; The caller must already have aligned RSP to 16 bytes.
  %rep %0 - 1
    %rotate -1
    push    qword %1
  %endrep
  %rotate -1
  %if %0 > 1
    pop rdi
  %endif
  %if %0 > 2
    pop rsi
  %endif
  %if %0 > 3
    pop rdx
  %endif
  %if %0 > 4
    pop rcx
  %endif
  %if %0 > 5
    pop r8
  %endif
  %if %0 > 6
    pop r9
  %endif
    call    %1
%endmacro

%macro scall 1-4 0, 0, 0
; system call
;   < (syscall number, param1, param2, param3) > rax
    push    rdi
    push    rsi
    push    rdx
    push    rcx
    push    r11
    push    qword %4
    push    qword %3
    push    qword %2
    pop rdi
    pop rsi
    pop rdx
    mov eax, %1
    syscall
    pop r11
    pop rcx
    pop rdx
    pop rsi
    pop rdi
%endmacro

%endif
sint2str.asmAssembly / 46 lines
%include "calls.inc"

global sint2str

section .text

sint2str:
    ; (signed int: edi, result: rsi) -> length in rax
    pbegin  0, rbx
    mov eax, edi        ; edi keeps the original sign
    cmp eax, 0
    jge .not_negative
    neg eax         ; unsigned magnitude, including INT_MIN
.not_negative:
    mov ebx, 10
    xor rcx, rcx
.lp:
    xor edx, edx
    div ebx
    add dl, '0'
    mov [rsi+rcx], dl
    inc ecx
    test    eax, eax
    jne .lp

    cmp edi, 0
    jge .reverse
    mov byte [rsi+rcx], '-'
    inc ecx
.reverse:
    push    rcx         ; save length
    dec ecx
    xor rbx, rbx
.lp2:
    cmp ebx, ecx
    jge .end
    mov al, [rsi+rbx]
    mov dl, [rsi+rcx]
    mov [rsi+rbx], dl
    mov [rsi+rcx], al
    inc ebx
    dec ecx
    jmp .lp2
.end:
    pop rax
    pend    rbx
tree-00.asmAssembly / 173 lines
%include "calls.inc"

%assign stack_len   1024
%assign num_len     12  ; sign + 10 digits + space

%assign start       0
%assign left_visited    1
%assign completed   2

%assign node_val    0   ; 4-byte int, then 4 bytes of padding
%assign node_left   8   ; 8-byte pointer
%assign node_right  16  ; 8-byte pointer
%assign node_size   24

%assign stack_p     0
%assign stack_st    8
%assign stack_size  16

%macro stack_push 3     ; (size_operand, node_pointer, state)
    inc dword %1
    push    qword %3
    push    qword %2
%endmacro

%macro stack_pop 1      ; (size_operand)
    dec dword %1
    add rsp, stack_size
%endmacro

global _start
extern sint2str

section .data

new_line    db 10

section .text

print_int:
    ; (val: edi)
    pbegin  16, rbx, r12        ; buffer + padding = 16 bytes
    lea rbx, [rbp-num_len]
    pcall   sint2str, rdi, rbx
    mov byte [rbx+rax], ' '
    lea r12, [rax+1]        ; length including space
.write:
    scall   1, 1, rbx, r12
    cmp rax, -4         ; interrupted: retry
    je  .write
    test    rax, rax
    jle .error
    add rbx, rax
    sub r12, rax
    jne .write
    pend    rbx, r12
.error:
    scall   60, 3


tree_push:
    ; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
    pbegin  0
    mov eax, [rdx]
    imul    rax, node_size
    add rax, rsi        ; tmp = &nodes[*nodes_used]
    inc dword [rdx]

    mov [rax+node_val], ecx
    mov qword [rax+node_left], 0
    mov qword [rax+node_right], 0
    mov [rdi], rax      ; *p = tmp
    pend

tree_insert:
    ; (p: rdi, nodes: rsi, nodes_used: rdx, val: ecx)
    pbegin  0
    mov rax, [rdi]
    test    rax, rax
    je  .new_node

    cmp ecx, [rax+node_val]
    jl  .left
    jg  .right
    jmp .end
.new_node:
    pcall   tree_push, rdi, rsi, rdx, rcx
    jmp .end
.left:
    lea rax, [rax+node_left]
    pcall   tree_insert, rax, rsi, rdx, rcx
    jmp .end
.right:
    lea rax, [rax+node_right]
    pcall   tree_insert, rax, rsi, rdx, rcx
.end:
    pend

tree_print1:
    ; (p: rdi)
    pbegin  8, rbx          ; padding + saved rbx = 16 bytes
    mov rbx, rdi
    test    rbx, rbx
    je  .end

    pcall   tree_print1, [rbx+node_left]
    mov eax, [rbx+node_val]
    pcall   print_int, rax
    pcall   tree_print1, [rbx+node_right]
.end:
    pend    rbx

tree_print:
    ; (p: rdi)
    ; [rbp-4] = size, rbx = current traversal record
    pbegin  8, rbx
    mov dword [rbp-4], 0
    test    rdi, rdi
    je  .end

    stack_push [rbp-4], rdi, start
.lp:
    cmp dword [rbp-4], 0
    je  .end
    mov rbx, rsp
    mov eax, [rbx+stack_st]
    cmp eax, start
    je  .start
    cmp eax, left_visited
    je  .left_visited
.completed:
    stack_pop [rbp-4]
    jmp .lp
.start:
    mov dword [rbx+stack_st], left_visited
    mov rax, [rbx+stack_p]
    mov rax, [rax+node_left]
    test    rax, rax
    je  .lp
    stack_push [rbp-4], rax, start
    jmp .lp
.left_visited:
    mov rax, [rbx+stack_p]
    mov eax, [rax+node_val]
    pcall   print_int, rax

    mov dword [rbx+stack_st], completed
    mov rax, [rbx+stack_p]
    mov rax, [rax+node_right]
    test    rax, rax
    je  .lp
    stack_push [rbp-4], rax, start
    jmp .lp
.end:
    pend    rbx

_start:
    ; [rbp-8] = p, [rbp-12] = nodes_used
    ; [rbp-(16+stack_len*node_size)] = nodes[0]
    mov rbp, rsp
    sub rsp, 16+stack_len*node_size
    mov qword [rbp-8], 0
    mov dword [rbp-12], 0
    lea rbx, [rbp-8]
    lea r12, [rbp-(16 + stack_len * node_size)]
    lea r13, [rbp-12]

    pcall   tree_insert, rbx, r12, r13, 1
    pcall   tree_insert, rbx, r12, r13, 3
    pcall   tree_insert, rbx, r12, r13, 2
    pcall   tree_print, [rbp-8]
    lea rax, [rel new_line]
    scall   1, 1, rax, 1
    scall   60, 0
tree-01.cC / 107 lines
#include <stdio.h>

enum { stack_len = 1024 };

enum state {
    start,
    left_visited,
    completed
};

struct node {
    int val;
    struct node *left, *right;
};

struct stack {
    const struct node *p;
    enum state st;
};

void stack_push(struct stack *s, int *size,
                const struct node *p, const enum state st)
{
    struct stack *tmp = &s[*size];
    (*size)++;
    tmp->p = p;
    tmp->st = st;
}

void stack_pop(int *size)
{
    (*size)--;
}

void tree_push(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    struct node *tmp = &nodes[*nodes_used];
    (*nodes_used)++;
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, struct node *nodes, int *nodes_used, int val)
{
    if (!*p)
        tree_push(p, nodes, nodes_used, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, nodes, nodes_used, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, nodes, nodes_used, val);
}

void tree_print1(const struct node *p)
{
    if (!p)
        return;
    tree_print1(p->left);
    printf("%d ", p->val);
    tree_print1(p->right);
}

void tree_print(const struct node *p)
{
    struct stack backpath[stack_len], *s;
    int size = 0;

    if (!p)
        return;

    stack_push(backpath, &size, p, start);
    while (size) {
        s = &backpath[size - 1];
        switch (s->st) {
            case start:
                s->st = left_visited;
                if (s->p->left)
                    stack_push(backpath, &size, s->p->left, start);
                break;
            case left_visited:
                printf("%d ", s->p->val);
                s->st = completed;
                if (s->p->right)
                    stack_push(backpath, &size, s->p->right, start);
                break;
            case completed:
                stack_pop(&size);
        }
    }
}

int main(void)
{
    struct node *p, nodes[stack_len];
    int nodes_used;

    p = NULL;
    nodes_used = 0;
    tree_insert(&p, nodes, &nodes_used, 1);
    tree_insert(&p, nodes, &nodes_used, 3);
    tree_insert(&p, nodes, &nodes_used, 2);
    tree_print(p);
    printf("\n");

    return 0;
}

9.2.2 Kinds of recursion

Simple, mutual, branching, and nested recursion create different dependency patterns. Array and tree sums provide practical examples, while Ackermann's function illustrates nested calls whose rapid growth makes direct evaluation expensive.

A linear recursion makes one call per level:

int array_sum2(const int *arr, int len)
{
    return len <= 0 ? 0 : *arr + array_sum2(arr + 1, len - 1);
}

A parallel recursion makes several calls per level, as in a tree:

struct node {
    int val;
    struct node *left, *right;
};

int tree_sum(const struct node *p)
{
    return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}
Detailed notes - 9.2.2: Kinds of recursion

1

factorial is a common teaching example, but not always a useful practical one

  • 21! exceeds the range of an ordinary 64-bit integer
  • small fixed-domain values can be tabulated
  • arbitrary-precision arithmetic is an alternative when large values matter

2

binomial coefficients need not be computed through large factorials

  • C(n+1,k) = C(n,k-1) + C(n,k)
  • Pascal's triangle avoids unnecessarily huge factorial intermediates
  • example: C(30,12) = 86493225

3

author prefers examples whose recursive structure arises in ordinary tasks

  • blanket claims that factorials are never useful are his teaching viewpoint

4

array sum:

  • empty/nonpositive-length case -> 0
  • otherwise first element + sum of the remaining array
  • arr+1 and len-1 describe that smaller problem
  • indexing versus dereferencing can express the same computation
  • ?: versus if does not by itself determine whether a function is pure

5

simple recursion: one recursive continuation per invocation

  • mutual recursion: f calls g, possibly through more functions, back to f
  • branching recursion: several recursive subproblems
  • independent subproblems can potentially run in parallel
  • tree sum combines left result + node value + right result
  • actual parallel execution requires an implementation that schedules it

6

nested recursion: a recursive result becomes input to another recursive call

  • shape: f(... f(...) ...)
  • Ackermann example:
    • A(0,n) = n+1
    • A(m,0) = A(m-1,1), for m > 0
    • A(m,n) = A(m-1,A(m,n-1)), for m,n > 0
  • total computable function that is not primitive recursive
  • grows extremely quickly; a direct recursive evaluator is not a practical way to obtain large values
Tests & experiments (3 files) - 9.2.2: Kinds of recursion
Section testrecursion-types (09-02-02)In catalog
MakefileMake / 12 lines
PROGRAMS = parallel

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
parallel.cC / 58 lines
#include <stdio.h>
#include <stdlib.h>

struct node {
    int val;
    struct node *left, *right;
};

void tree_push(struct node **p, int val)
{
    struct node *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, int val)
{
    if (!*p)
        tree_push(p, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, val);
}

void tree_print(const struct node *p)
{
    if (!p)
        return;
    tree_print(p->left);
    printf("%d ", p->val);
    tree_print(p->right);
}

int tree_sum(const struct node *p)
{
    return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}

int main()
{
    struct node *p;

    p = NULL;
    tree_insert(&p, 1);
    tree_insert(&p, 3);
    tree_insert(&p, 2);
    tree_insert(&p, 3);
    tree_print(p);
    printf("\n");

    int sum = tree_sum(p);
    printf("%d\n", sum);

    return 0;
}
primitive.cC / 23 lines
#include <stdio.h>

int array_sum1(const int arr[], int len)
{
    if (len <= 0)
        return 0;
    return arr[0] + array_sum1(&(arr[1]), len - 1);
}

int array_sum2(const int *arr, int len)
{
    return len <= 0 ? 0 : *arr + array_sum2(arr + 1, len - 1);
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int len = sizeof(arr) / sizeof(*arr);
    int sum1 = array_sum1(arr, len);
    int sum2 = array_sum2(arr, len);
    printf("%d %d\n", sum1, sum2);
    return 0;
}

9.2.3 Reducing or folding a sequence

A fold combines sequence elements with a seed and a supplied operation. Left and right folds group operands differently, which changes results for some operations and determines whether recursive calls leave work pending.

Left and right folds over a list, with the combining function as a parameter:

typedef int (*funptr)(int, int);

struct item {
    int val;
    struct item *next;
};

int list_reduce_l(funptr f, int i, struct item *l)
{
    return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}

int list_reduce_r(funptr f, int i, struct item *l)
{
    return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}

The same folds compute a sum, a product, a maximum and a count by changing only the function:

Show the complete program
#include <stdio.h>
#include <stdlib.h>

typedef int (*funptr)(int, int);

struct item {
    int val;
    struct item *next;
};

void item_push(struct item **p, int val)
{
    struct item *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->next = *p;
    *p = tmp;
}

void item_pop(struct item **p)
{
    struct item *tmp = *p;
    (*p) = (*p)->next;
    free(tmp);
}

int list_reduce_l1(funptr f, int i, struct item *l)
{
    int new_i;
    if (!l)
        return i;
    new_i = f(i, l->val);
    return list_reduce_l1(f, new_i, l->next);
}

int list_reduce_r1(funptr f, int i, struct item *l)
{
    int rest_res;
    if (!l)
        return i;
    rest_res = list_reduce_r1(f, i, l->next);
    return f(l->val, rest_res);
}

int list_reduce_l(funptr f, int i, struct item *l)
{
    return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}

int list_reduce_r(funptr f, int i, struct item *l)
{
    return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}

int plus(int x, int y) { return x + y; }
int mul(int x, int y) { return x * y; }
int max(int x, int y) { return x > y ? x : y; }
int zero_count_l(int n, int x) { return x == 0 ? n + 1 : n; }
int zero_count_r(int x, int n) { return x == 0 ? n + 1 : n; }

int main()
{
    int sum, product, maximum, num_zeros;
    struct item *p = NULL;

    item_push(&p, 1);
    item_push(&p, 2);
    item_push(&p, 3);
    item_push(&p, 0);
    item_push(&p, 4);

    sum = list_reduce_l(plus, 0, p);
    product = list_reduce_l(mul, 1, p);
    maximum = list_reduce_l(max, p->val, p->next);
    num_zeros = list_reduce_l(zero_count_l, 0, p);

    sum = list_reduce_r(plus, 0, p);
    product = list_reduce_r(mul, 1, p);
    maximum = list_reduce_r(max, p->val, p->next);
    num_zeros = list_reduce_r(zero_count_r, 0, p);

    printf("sum: %d\n", sum);
    printf("mul: %d\n", product);
    printf("max: %d\n", maximum);
    printf("num zeros: %d\n", num_zeros);
    return 0;
}
sum: 10
mul: 0
max: 4
num zeros: 1
Detailed notes - 9.2.3: Reducing or folding a sequence

1

fold combines sequence elements with an initial accumulator/seed

  • empty sequence returns the seed
  • sum: addition with seed 0
  • product: multiplication with seed 1
  • maximum: take the first element as seed, requiring a nonempty sequence

2

left fold groups from the left:

  • f(f(f(seed,a1),a2),a3)
  • accumulator is the first argument in the convention used below
  • right fold: f(a1,f(a2,f(a3,seed)))
  • order and operand roles matter when f is not associative/commutative
  • accumulator type need not equal element type
  • filtering is possible when the accumulator itself is a list

3

recursion expresses the dependency structure of folds

  • left fold can also be a simple accumulator loop
  • right fold on a singly linked list must first handle the remaining tail
  • an iterative version can retain/reverse elements explicitly

4

C illustration uses integer nodes and intfunptr = int (*)(int,int)

  • left: reduce_l(f, f(seed, head), tail)
  • right: f(head, reduce_r(f, seed, tail))
  • empty list returns seed in both cases
  • left fold computes the new seed before its recursive call

5

right fold must wait for the tail result before calling f

  • expanded code names rest_res to make that dependency explicit

6

left-fold recursive call is in tail position

  • right-fold recursive call is followed by another computation
  • this affects whether a frame can be reused

7

supply arithmetic helpers as fold arguments

  • addition/0 -> sum; multiplication/1 -> product
  • maximum starts with head value and folds the remaining tail
  • respect overflow limits of the chosen integer type

8

zero-counting helper must match operand order

  • left helper takes count, element
  • right helper takes element, count
  • zero element increments the count; other elements preserve it
  • seed is 0

9

examples illustrate the abstraction rather than prescribing a C optimization

  • performance depends on compiler, calling overhead, and representation
  • later languages make generic folds easier to express
Subtraction exposes the difference: changing the fold direction changes the expression.
A fold chooses the nesting of operations. Open full size - Editable SVG
Examples & tests (4 files) - 9.2.3: Reducing or folding a sequence
Book exampleBook example: reduce_ls.cIn catalog
reduce_ls.cC / 105 lines
#include <stdio.h>
#include <stdlib.h>


struct item {
    int val;
    struct item *next;
};

typedef int (*intfunptr)(int, int);


#ifdef SHORT_VERS
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
    return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
    return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}
#else
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
    int new_i;
    if(!ls)
        return i;
    new_i = f(i, ls->val);
    return intlist_reduce_l(f, new_i, ls->next);
}
int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
    int rest_res;
    if(!ls)
        return i;
    rest_res = intlist_reduce_r(f, i, ls->next);
    return f(ls->val, rest_res);
}
#endif

int int_plus(int x, int y) { return x + y; }
int int_mul(int x, int y) { return x * y; }
int int_max(int x, int y) { return x > y ? x : y; }
int int_zcnt_left(int n, int x) { return x==0 ? n+1 : n; }
int int_zcnt_right(int x, int n) { return x==0 ? n+1 : n; }


struct item* array2list(int *a, int n)
{
    struct item *p;
    if(!n)
        return NULL;
    p = malloc(sizeof(*p));
    p->val = *a;
    p->next = array2list(a+1, n-1);
    return p;
}

void freelist(struct item *p)
{
    if(!p)
        return;
    freelist(p->next);
    free(p);
}

int main()
{
    int s, p, ma, mb, z1, z2;

    int a[] = { 1,2,3,4,5,6,7,8 };
    int b[] = { 1,2,0,13,4,15,61,7,0,8 };

    struct item *lsa = array2list(a, 8);
    struct item *lsb = array2list(b, 10);

#ifdef SHORT_VERS
    printf("using short versions...\n");
#endif

    s = intlist_reduce_l(int_plus, 0, lsa);
    p = intlist_reduce_l(int_mul, 1, lsa);
    printf("%d %d\n", s, p);
    s = intlist_reduce_l(int_plus, 0, lsb);
    p = intlist_reduce_l(int_mul, 1, lsb);
    printf("%d %d\n", s, p);
    s = intlist_reduce_r(int_plus, 0, lsa);
    p = intlist_reduce_r(int_mul, 1, lsa);
    printf("%d %d\n", s, p);
    s = intlist_reduce_r(int_plus, 0, lsb);
    p = intlist_reduce_r(int_mul, 1, lsb);
    printf("%d %d\n", s, p);

    ma = intlist_reduce_l(int_max, lsa->val, lsa->next);
    mb = intlist_reduce_l(int_max, lsb->val, lsb->next);
    printf("%d %d\n", ma, mb);


    z1 = intlist_reduce_l(int_zcnt_left, 0, lsb);
    z2 = intlist_reduce_r(int_zcnt_right, 0, lsb);
    printf("%d %d\n", z1, z2);


    return 0;
}
Section testreduction (09-02-03)In catalog
MakefileMake / 12 lines
PROGRAMS = reduce reduce_loop

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
reduce.cC / 85 lines
#include <stdio.h>
#include <stdlib.h>

typedef int (*funptr)(int, int);

struct item {
    int val;
    struct item *next;
};

void item_push(struct item **p, int val)
{
    struct item *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->next = *p;
    *p = tmp;
}

void item_pop(struct item **p)
{
    struct item *tmp = *p;
    (*p) = (*p)->next;
    free(tmp);
}

int list_reduce_l1(funptr f, int i, struct item *l)
{
    int new_i;
    if (!l)
        return i;
    new_i = f(i, l->val);
    return list_reduce_l1(f, new_i, l->next);
}

int list_reduce_r1(funptr f, int i, struct item *l)
{
    int rest_res;
    if (!l)
        return i;
    rest_res = list_reduce_r1(f, i, l->next);
    return f(l->val, rest_res);
}

int list_reduce_l(funptr f, int i, struct item *l)
{
    return l ? list_reduce_l(f, f(i, l->val), l->next) : i;
}

int list_reduce_r(funptr f, int i, struct item *l)
{
    return l ? f(l->val, list_reduce_r(f, i, l->next)) : i;
}

int plus(int x, int y) { return x + y; }
int mul(int x, int y) { return x * y; }
int max(int x, int y) { return x > y ? x : y; }
int zero_count_l(int n, int x) { return x == 0 ? n + 1 : n; }
int zero_count_r(int x, int n) { return x == 0 ? n + 1 : n; }

int main()
{
    int sum, product, maximum, num_zeros;
    struct item *p = NULL;

    item_push(&p, 1);
    item_push(&p, 2);
    item_push(&p, 3);
    item_push(&p, 0);
    item_push(&p, 4);

    sum = list_reduce_l(plus, 0, p);
    product = list_reduce_l(mul, 1, p);
    maximum = list_reduce_l(max, p->val, p->next);
    num_zeros = list_reduce_l(zero_count_l, 0, p);

    sum = list_reduce_r(plus, 0, p);
    product = list_reduce_r(mul, 1, p);
    maximum = list_reduce_r(max, p->val, p->next);
    num_zeros = list_reduce_r(zero_count_r, 0, p);

    printf("sum: %d\n", sum);
    printf("mul: %d\n", product);
    printf("max: %d\n", maximum);
    printf("num zeros: %d\n", num_zeros);
}
reduce_loop.cC / 94 lines
#include <stdio.h>
#include <stdlib.h>

struct item {
    int val;
    struct item *next;
};

typedef int (*intfunptr)(int, int);

/* the two recursive versions from the book */
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
    return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}

int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
    return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}

/* left reduction as a loop: i holds the result so far */
int intlist_reduce_l_loop(intfunptr f, int i, struct item *ls)
{
    for (; ls; ls = ls->next)
        i = f(i, ls->val);
    return i;
}

/* right reduction as a loop: possible for an array, walked backwards */
int intarray_reduce_r_loop(intfunptr f, int i, const int *arr, int len)
{
    int k;
    for (k = len - 1; k >= 0; k--)
        i = f(arr[k], i);
    return i;
}

void push(struct item **ls, int val)
{
    struct item *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->next = *ls;
    *ls = tmp;
}

void pop(struct item **ls)
{
    struct item *tmp = *ls;
    *ls = (*ls)->next;
    free(tmp);
}

/* ... and for a list only through a reversed copy */
int intlist_reduce_r_loop(intfunptr f, int i, struct item *ls)
{
    struct item *rev = NULL;
    for (; ls; ls = ls->next)
        push(&rev, ls->val);

    while (rev) {
        i = f(rev->val, i);
        pop(&rev);
    }
    return i;
}

struct item *make_list(const int *arr, int len)
{
    struct item *first = NULL;
    int k;
    for (k = len - 1; k >= 0; k--)
        push(&first, arr[k]);
    return first;
}

int sub(int x, int y) { return x - y; }

int main()
{
    int arr[] = { 1, 2, 3, 4 };
    struct item *ls = make_list(arr, 4), *tmp;
    printf("left,  recursion: %d\n", intlist_reduce_l(sub, 0, ls));
    printf("left,  loop:      %d\n", intlist_reduce_l_loop(sub, 0, ls));
    printf("right, recursion: %d\n", intlist_reduce_r(sub, 0, ls));
    printf("right, array:     %d\n", intarray_reduce_r_loop(sub, 0, arr, 4));
    printf("right, list:      %d\n", intlist_reduce_r_loop(sub, 0, ls));
    while (ls) {
        tmp = ls;
        ls = ls->next;
        free(tmp);
    }
    return 0;
}

9.2.4 Tail recursion

A tail call returns its callee's result without further work, allowing implementations to reuse the current frame. Accumulators expose tail positions, but unresolved branches still require storage, and C does not guarantee tail-call optimization.

list_len must add 1 after its recursive call returns. list_len_do1 carries the count in an accumulator, so its recursive call is the last action: a tail call:

struct item {
    int val;
    struct item *next;
};

int list_len(const struct item *p)
{
    return p ? list_len(p->next) + 1 : 0;
}

int list_len_do1(const struct item *p, int count)
{
    return p ? list_len_do1(p->next, count + 1) : count;
}

int list_len1(const struct item *p)
{
    return list_len_do1(p, 0);
}
Detailed notes - 9.2.4: Tail recursion

1

recursive list search:

  • empty list -> NULL
  • matching head -> head address
  • otherwise return find_value(next, value) directly
  • nothing remains to do after that recursive call
  • reusing the caller's frame can avoid a chain of redundant returns

2

self-tail-call can be modeled as updating parameters and restarting the body

  • preserve the original return destination
  • source illustrates this with a backward goto
  • the goto version explains an optimization, not a preferred source style

3

an ordinary loop expresses the same repeated search

  • indirect/mutual tail calls require a more general transformation

4

wildcard matcher uses match and starmatch

  • empty pattern matches only empty input
  • main recursion progressively removes pattern characters
  • star handling explores possible lengths of the matched substring

5

ordinary character / ? case:

  • reject exhausted input
  • reject a differing character unless the pattern has ?
  • otherwise tail-call match on both remaining suffixes

6

leading * delegates to starmatch

  • preserve the current input suffix
  • remove the star from the pattern passed onward

7

first try matching the star against an empty substring

  • call match with unchanged input and the remaining pattern
  • this is mutual recursion between match and starmatch

8

failed alternative does not yet mean complete failure

  • if input remains, try consuming one more character for the star
  • tail-call starmatch with shorter input
  • exhausted input ends the alternatives

9

only unresolved alternatives need retained continuation state

  • starmatch must remember where to retry after a failed match
  • other calls returning a callee's result directly need no later work

10

last alternative needs no retry state

  • when input is empty, return match("", remaining_pattern) directly
  • moving that base case first makes the final attempt a tail call

11

if all eligible tail calls were optimized, retained frames would represent unresolved stars rather than every consumed character

  • C does not guarantee this optimization
  • particular compilers can optimize self and some mutual/sibling calls
  • book's claim that C compilers cannot do mutual tail calls is too broad

12

recognizing tail position does not promise a particular machine-code result

  • compiler, ABI, optimization settings, and object lifetimes matter

13

reusing a frame must preserve arguments still needed to compute new ones

  • parameter placement and live values can complicate transformation
  • temporary moves/copies may be needed
  • this is a potential constraint, not proof that tail calls are always slower

14

optimizers balance execution cost and resource use

  • a language that relies on proper tail calls gives different guarantees from C's optional optimizations

15

list_length(next) + 1 is not itself a tail call

  • addition remains after the recursive result arrives
  • being textually inside return is not sufficient

16

accumulator parameter moves pending work before the recursive call

  • list_length_do(list, count): empty -> count
  • otherwise recurse on next with count+1
  • wrapper starts count at 0
  • array sum similarly passes the accumulated sum to the next call
  • reversing a list can move each head onto an accumulated result list
  • save next before changing the link; begin result at NULL
  • this link-reversal algorithm is linear rather than repeatedly appending through the whole growing result

17

an accumulator cannot erase every outstanding branch

  • tree sum still must resume after processing one subtree
  • one recursive call may be tail-positioned while the other is not
  • eliminating all frames requires storing unfinished nodes elsewhere
  • explicit stack and tail-recursive encodings preserve equivalent work
Compare a pending addition with a direct return of the next call.
A tail call leaves no work for its caller. Open full size - Editable SVG
Examples & tests (12 files) - 9.2.4: Tail recursion
Book exampleBook example: match_rec.cIn catalog
match_rec.cC / 52 lines
#include <stdio.h>

int starmatch(const char *str, const char *pat);

int match(const char *str, const char *pat)
{
    switch(*pat) {
        case 0:
            return *str == 0;
        case '*':
            return starmatch(str, pat+1);
        default:
            if(!*str || (*str != *pat && *pat != '?'))
                return 0;
            return
                match(str+1, pat+1);
    }
}

#if 1
int starmatch(const char *str, const char *pat)
{
    if(match(str, pat))
        return 1;
    if(!*str)
        return 0;
    return starmatch(str+1, pat);
}
#else
int starmatch(const char *str, const char *pat)
{
    if(!*str)
        return match("", pat);
    if(match(str, pat))
        return 1;
    return starmatch(str+1, pat);
}
#endif


int main(int argc, const char **argv)
{
    if(argc < 3) {
        printf("Need two arguments\n");
        return 1;
    }
    if(match(argv[1], argv[2]))
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}
Section testtail (09-02-04)In catalog
MakefileMake / 18 lines
PROGRAMS = accumulator reverse reverse1 reverse2 tree_sum

SRCMODULES = list.c tree.c
OBJMODULES = $(SRCMODULES:.c=.o)

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
accumulator.cC / 54 lines
#include <stdio.h>

#include "list.h"

int list_len(const struct item *p)
{
    return p ? list_len(p->next) + 1 : 0;
}

int list_len_do1(const struct item *p, int count)
{
    return p ? list_len_do1(p->next, count + 1) : count;
}

int list_len1(const struct item *p)
{
    return list_len_do1(p, 0);
}

int array_sum_do(int *arr, int len, int sum)
{
    return len ? array_sum_do(arr + 1, len - 1, sum + *arr) : sum;
}

int array_sum(int *arr, int len)
{
    return array_sum_do(arr, len, 0);
}

int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int len = sizeof(arr) / sizeof(*arr);
    int sum = array_sum(arr, len);
    printf("sum: %d\n", sum);

    struct item *p = NULL;

    list_push(&p, 3);
    list_push(&p, 2);
    list_push(&p, 1);

    int len0 = list_len(p);
    printf("len: %d\n", len0);

    int len1 = list_len(p);
    printf("len1: %d\n", len1);

    list_pop(&p);
    list_pop(&p);
    list_pop(&p);

    return 0;
}
list.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>

#include "list.h"

void list_push(struct item **p, int val)
{
    struct item *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->next = *p;
    *p = tmp;
}

int list_pop(struct item **p)
{
    struct item *tmp = *p;
    int val = tmp->val;
    *p = (*p)->next;
    free(tmp);
    return val;
}

void list_print(const struct item *p)
{
    for (; p; p = p->next)
        printf("%d ", p->val);
    printf("\n");
}
list.hC / 9 lines
struct item {
    int val;
    struct item *next;
};

void list_push(struct item **p, int val);
int list_pop(struct item **p);
void list_print(const struct item *p);

match.cC / 40 lines
#include <stdio.h>

int starmatch(const char *str, const char *pat);

int match(const char *pat, const char *str)
{
    switch (*pat) {
        case 0:
            return *str == 0;
        case '*':
            return starmatch(pat + 1, str);
        default:
            if (!*str || (*str != *pat && *pat != '?'))
                return 0;
            return match(pat + 1, str + 1);
    }
}

int starmatch(const char *pat, const char *str)
{
    if (match(pat, str))
        return 1;
    if (!*str)
        return 0;
    return starmatch(pat, str + 1);
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <pattern <string>\n", argv[0]);
        return 1;
    }
    if (match(argv[1], argv[2]))
        printf("matched\n");
    else
        printf("does not match\n");

    return 0;
}
reverse.cC / 36 lines
#include <stdio.h>

#include "list.h"

struct item *list_reverse_do(struct item *dst, struct item *src)
{
    struct item *tmp;
    if (!src)
        return dst;
    tmp = src->next;
    src->next = dst;
    return list_reverse_do(src, tmp);
}

struct item *list_reverse(struct item *src)
{
    return list_reverse_do(NULL, src);
}

int main()
{
    struct item *p = NULL;

    list_push(&p, 3);
    list_push(&p, 2);
    list_push(&p, 1);

    struct item *rev = list_reverse(p);
    list_print(rev);

    list_pop(&rev);
    list_pop(&rev);
    list_pop(&rev);

    return 0;
}
reverse1.cC / 35 lines
#include <stdio.h>
#include "list.h"

struct item *list_iterate(struct item *p)
{
    return !p->next ? p : list_iterate(p->next);
}

struct item *list_reverse(struct item *p)
{
    struct item *rev, *last;
    if (!p || !p->next)
        return p;
    rev = list_reverse(p->next);
    last = list_iterate(rev);
    last->next = p;
    p->next = NULL;
    return rev;
}

int main()
{
    struct item *p = NULL;

    list_push(&p, 4);
    list_push(&p, 3);
    list_push(&p, 2);
    list_push(&p, 1);

    list_print(p);
    struct item *rev = list_reverse(p);
    list_print(rev);

    return 0;
}
reverse2.cC / 39 lines
#include <stdio.h>
#include "list.h"

struct item *list_reverse(struct item *curr)
{
    struct item *prev, *next;
    for (prev = NULL; curr; prev = curr, curr = next) {
        next = curr->next;
        curr->next = prev;
    }
    return prev;
}

struct item *list_reverse1(struct item *p)
{
    struct item *rev;
    if (!p || !p->next)
        return p;
    rev = list_reverse1(p->next);
    p->next->next = p;
    p->next = NULL;
    return rev;
}

int main()
{
    struct item *p = NULL;

    list_push(&p, 4);
    list_push(&p, 3);
    list_push(&p, 2);
    list_push(&p, 1);

    list_print(p);
    struct item *rev = list_reverse1(p);
    list_print(rev);

    return 0;
}
tree.cC / 72 lines
#include <stdio.h>
#include <stdlib.h>

#include "tree.h"

void tree_push(struct node **p, int val)
{
    struct node *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    *p = tmp;
}

void tree_insert(struct node **p, int val)
{
    if (!*p)
        tree_push(p, val);
    else if (val < (*p)->val)
        tree_insert(&(*p)->left, val);
    else if (val > (*p)->val)
        tree_insert(&(*p)->right, val);
}

void tree_print(const struct node *p)
{
    if (!p)
        return;
    tree_print(p->left);
    printf("%d ", p->val);
    tree_print(p->right);
}

void stack_push(struct stack **s, const struct node *p)
{
    struct stack *tmp = malloc(sizeof(*tmp));
    tmp->p = p;
    tmp->next = *s;
    *s = tmp;
}

const struct node *stack_pop(struct stack **s)
{
    struct stack *tmp = *s;
    const struct node *p = tmp->p;
    *s = (*s)->next;
    free(tmp);
    return p;
}

void stack_init1(struct stack1 *s, int capacity)
{
    s->p = malloc(capacity * sizeof(*s->p));
    s->capacity = capacity;
    s->size = 0;
}

void stack_push1(struct stack1 *s, const struct node *p)
{
    if (s->size == s->capacity) {
        s->capacity *= 2;
        s->p = realloc(s->p, s->capacity * sizeof(*s->p));
    }
    s->p[s->size] = p;
    s->size++;
}

const struct node *stack_pop1(struct stack1 *s)
{
    s->size--;
    return s->p[s->size];
}
tree.hC / 26 lines
struct node {
    int val;
    struct node *left, *right;
};

struct stack {
    const struct node *p;
    struct stack *next;
};

struct stack1 {
    const struct node **p;
    int size;
    int capacity;
};

void tree_push(struct node **p, int val);
void tree_insert(struct node **p, int val);
void tree_print(const struct node *p);

void stack_push(struct stack **s, const struct node *p);
const struct node *stack_pop(struct stack **s);

void stack_init1(struct stack1 *s, int capacity);
void stack_push1(struct stack1 *s, const struct node *p);
const struct node *stack_pop1(struct stack1 *s);
tree_sum.cC / 114 lines
#include <stdio.h>
#include <stdlib.h>

#include "tree.h"

int tree_sum(const struct node *p)
{
    return p ? tree_sum(p->left) + p->val + tree_sum(p->right) : 0;
}

int tree_sum_do1(const struct node *p, int sum)
{
    if (!p)
        return sum;
    sum = tree_sum_do1(p->left, sum);
    return tree_sum_do1(p->right, sum + p->val);
}

int tree_sum1(const struct node *p)
{
    return tree_sum_do1(p, 0);
}

int tree_sum_do2(const struct node *p, int sum, struct stack *s)
{
    if (!p)
        return sum;
    if (p->left)
        stack_push(&s, p->left);
    if (p->right)
        return tree_sum_do2(p->right, sum + p->val, s);
    if (s) {
        const struct node *tmp = stack_pop(&s);
        return tree_sum_do2(tmp, sum + p->val, s);
    }
    return sum + p->val;
}

int tree_sum2(const struct node *p)
{
    return tree_sum_do2(p, 0, NULL);
}

int tree_sum_do3(const struct node *p, int sum, struct stack *s)
{
    if (p) {
        stack_push(&s, p);
        return tree_sum_do3(p->left, sum, s);
    }
    if (s) {
        const struct node *tmp = stack_pop(&s);
        return tree_sum_do3(tmp->right, sum + tmp->val, s);
    }
    return sum;
}

int tree_sum3(const struct node *p)
{
    return tree_sum_do3(p, 0, NULL);
}

int tree_sum_do4(const struct node *p, int sum, struct stack1 *s)
{
    if (p) {
        stack_push1(s, p);
        return tree_sum_do4(p->left, sum, s);
    }
    if (s->size) {
        const struct node *tmp = stack_pop1(s);
        return tree_sum_do4(tmp->right, sum + tmp->val, s);
    }
    return sum;
}

int tree_sum4(const struct node *p)
{
    int sum;
    struct stack1 s;
    stack_init1(&s, 1);
    sum = tree_sum_do4(p, 0, &s);
    free(s.p);
    return sum;
}

int main()
{
    int sum;
    struct node *p;

    p = NULL;
    tree_insert(&p, 2);
    tree_insert(&p, 3);
    tree_insert(&p, 1);
    tree_insert(&p, 4);
    tree_print(p);
    printf("\n");

    sum = tree_sum(p);
    printf("%d\n", sum);

    sum = tree_sum1(p);
    printf("%d\n", sum);

    sum = tree_sum2(p);
    printf("%d\n", sum);

    sum = tree_sum3(p);
    printf("%d\n", sum);

    sum = tree_sum4(p);
    printf("%d\n", sum);

    return 0;
}

9.2.5 Recursive thinking

Recursive thinking can characterize a result structurally or trace actions through descent and return. A string-copy example allocates at the deepest call and fills characters while returning, showing why execution order sometimes remains essential.

Etude 9.01 states the maximum of an array recursively: the maximum of one element is that element; otherwise it is the larger of the first element and the maximum of the rest:

#include <stdio.h>

int vecmax(const int *arr, int len)
{
    int submax = (len == 1 ? *arr : vecmax(arr + 1, len - 1));
    return submax > *arr ? submax : *arr;
}

int main()
{
    int i;
    int array[] = { 2, 8, 11, 1, 9, 4, 6 };
    int len = sizeof(array) / sizeof(*array);
    int max = vecmax(array, len);

    for (i = 0; i < len; i++)
        printf("%d ", array[i]);
    printf("\nmax: %d\n", max);

    return 0;
}
2 8 11 1 9 4 6
max: 11

A recursive strdup learns the length only at the deepest call, so it allocates there and stores the characters on the way back:

char *strdup_rec_do1(const char *str, int depth)
{
    char *res;
    if (*str)
        res = strdup_rec_do1(str + 1, depth + 1);
    else
        res = malloc(depth + 1);
    res[depth] = *str;
    return res;
}

Etude 9.06 finds a substring without loops. The checking flag distinguishes comparing a candidate match from moving the start of the search:

#include <stdio.h>

static const char *strstr_do(const char *str, const char *sub, int checking);

static const char *strstr_helper(const char *str, const char *sub, int checking)
{
    if (checking)
        return NULL;
    else
        return strstr_do(str + 1, sub, 0);
}

static const char *strstr_do(const char *str, const char *sub, int checking)
{
    if (*str == 0)
        return *sub == 0 ? str : NULL;
    else if (*sub == 0)
        return str;
    else if (*str == *sub)
        return strstr_do(str + 1, sub + 1, 1) ? str : strstr_helper(str, sub, checking);
    else
        return strstr_helper(str, sub, checking);
}

static char *strstr(const char *str, const char *sub)
{
    return (char *) strstr_do(str, sub, 0);
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <str> <sub>\n", argv[0]);
        return 1;
    }

    const char *res = strstr(argv[1], argv[2]);
    if (res != NULL)
        printf("%s\n", res);
    else
        printf("Have not found\n");

    return 0;
}
issippi
Detailed notes - 9.2.5: Recursive thinking

1

using recursive calls does not automatically mean thinking recursively

  • an operational account may still describe a sequence of actions

2

two descriptions of list length:

  • operational: compute tail length, then add one
  • structural: empty length is zero; other length is tail length plus one
  • second directly characterizes the result on recursively defined data
  • it need not first be rewritten as an instruction-by-instruction story

3

nested fold expressions expose the recursive structure

  • left grouping and right grouping show how results are composed
  • a sequence of r1, r2, ... updates emphasizes an operational interpretation

4

accumulator-based recursion often invites operational reasoning

  • explain what has been accumulated and what remains
  • structural definitions are not always the clearest description

5

recursive string-copy example uses descent and return phases

  • descend while tracking position/depth to find the required length
  • at the terminator, allocate depth+1 bytes
  • while returning, each frame writes its character at its saved index
  • every level returns the same newly allocated result address
  • allocation failure must be handled before any writes in real code

6

ordering is essential in that example

  • storage must exist before characters are copied into it
  • other algorithms use returning calls to reverse the order of actions

7

both structural and operational explanations have uses

  • choose the one that exposes the essential dependencies of the task

8

recursion as technique: direct or indirect self-invocation

  • recursion as paradigm: a particular way of understanding the problem
  • technical usefulness does not depend on always adopting that paradigm
Examples & tests (3 files) - 9.2.5: Recursive thinking
Book exampleBook example: strdup_rec.cIn catalog
strdup_rec.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>

char *strdup_rec_do(const char *str, int depth)
{
    char *res;
    if(*str)
        res = strdup_rec_do(str+1, depth+1);
    else
        res = malloc(depth+1);
    res[depth] = *str;
    return res;
}
char *strdup_rec(const char *str)
{
    return strdup_rec_do(str, 0);
}

int main(int argc, char**argv)
{
    char *s = strdup_rec(argv[0]);
    puts(s);
    free(s);
    return 0;
}
Section testapproach (09-02-05)In catalog
MakefileMake / 12 lines
PROGRAMS = strdup_rec

CC = gcc
CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
strdup_rec.cC / 37 lines
#include <stdio.h>
#include <stdlib.h>

char *strdup_rec_do1(const char *str, int depth)
{
    char *res;
    if (*str)
        res = strdup_rec_do1(str + 1, depth + 1);
    else
        res = malloc(depth + 1);
    res[depth] = *str;
    return res;
}

char *strdup_rec_do(const char *str, int depth)
{
    char *res = *str ? strdup_rec_do(str + 1, depth + 1) : malloc(depth + 1);
    res[depth] = *str;
    return res;
}

char *strdup_rec(const char *str)
{
    return strdup_rec_do1(str, 0);
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <string>\n", argv[0]);
        return 1;
    }
    char *dup = strdup_rec(argv[1]);
    printf("%s\n%s\n", argv[1], dup);
    free(dup);
    return 0;
}

9.3 Paradigms and programming languages

Languages supply concepts as well as notation, encouraging some approaches and making others awkward. Comparing their influence on thought requires looking beyond surface syntax to expression semantics and practical delivery constraints.

9.3.1 The role of language

Available operations can suggest better algorithms, as sorting repeated sequence windows replaces pairwise comparison. A language can require, encourage, merely permit, or impede a paradigm without uniquely determining the programmer's solution.

Detailed notes - 9.3.1: The role of language

1

language supplies concepts as well as notation for expressing a solution

  • book cites Barron and Dijkstra on tools shaping thought
  • Budd's example searches a long DNA-like sequence for repeated windows
  • direct solution compares every pair of starting positions
  • comparing fixed-length prefixes gives roughly quadratic pairwise work

2

alternative uses a sortable collection of windows

  • create one row per length-k window plus its original starting index
  • sort by the k data elements, not the saved position
  • equal windows become adjacent
  • scan groups to recover their original positions
  • for fixed k, sorting costs O(N log N)

3

algorithmic improvement can dominate implementation overhead

  • sorting-based approach can also be implemented in other languages
  • availability of a natural sorting operation may suggest it sooner
  • enumerating every matching pair can add output-size-dependent work

4

language communities develop habits and conventions

  • author argues these influence the solutions programmers notice
  • the anecdote does not prove a language uniquely determines an algorithm

5

one paradigm label rarely describes an entire language

  • languages can support several models
  • same paradigm can be expressed using different languages

6

book proposes seven relationships between a language and a paradigm:

  • require: cannot avoid it
  • strongly pressure: alternatives exist but are awkward
  • encourage: using it offers a practical advantage
  • support: supplies dedicated facilities
  • permit: can implement it without special facilities
  • impede: possible only with substantial inconvenience
  • prohibit: cannot express it within the intended model

7

illustrative classifications from the author

  • Smalltalk centers object-oriented interaction
  • imperative numerical languages center assignment
  • Lisp encourages recursive formulations
  • these are conceptual comparisons, not complete language specifications

8

C++ offers several independently useful models

  • ADTs, objects/inheritance, templates, exceptions
  • programmer can adopt some without adopting all
  • Lisp's higher-order functions and lambdas similarly reward a new style

9

having a feature is distinct from making it the preferred style

  • Lisp loops, C++ macros, C recursion illustrate that distinction

10

a skilled programmer can impose conventions beyond direct syntax support

  • C can represent objects as structures and methods as functions
  • function-pointer tables supply dynamic dispatch
  • embedding a common structure can model shared interface/layout
  • Linux VFS illustrates such object-oriented organization in C

11

C macro-based generic code can be cumbersome

  • setjmp/longjmp alone also do not provide a complete exception system
  • required bookkeeping can discourage a paradigm despite its expressibility

12

historical languages without localized subprogram state restrict recursion

  • sufficiently elaborate manual encodings can change what is possible
  • author's examples of "prohibition" concern ordinary practical language use
Tests & experiments (32 files) - 9.3.1: The role of language
Section testlanguages-00 (09-03-01)In catalog
MakefileMake / 18 lines
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test

SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)

CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic

all: $(PROGRAMS)

%.o: %.c %.h
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES)
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
apl.cC / 12 lines
#include "matrix.h"
#include "apl.h"

void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
    int i;
    for (i = 0; i < rows - 1; i++)
        if (array_compare(a[i], a[i+1], min) == 0) {
            array_push(res, a[i][min]);
            array_push(res, a[i+1][min]);
        }
}
apl.hC / 9 lines
#ifndef APL_H
#define APL_H

#include "array.h"
#include "matrix.h"

void apl_find_repeating(int (*a)[cols], int rows, struct array *res);

#endif
apl_test.cC / 35 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"
#include "matrix.h"
#include "apl.h"

int main()
{
    struct array res;
    int arr[] = {
        8, 3, 5, 7, 2, 4,
        99, 99,
        3, 5, 7, 2, 4,
        10
    };
    int len = sizeof(arr) / sizeof(*arr);
    int rows = len - min + 1;
    int (*matrix)[cols] = malloc(rows * sizeof(*matrix));

    matrix_create(arr, len, matrix);
    matrix_print(matrix, rows);
    printf("\n");
    matrix_merge_sort(matrix, 0, rows - 1);
    matrix_print(matrix, rows);

    array_init(&res, 1);
    apl_find_repeating(matrix, rows, &res);
    array_print(res);
    array_clean(&res);

    free(matrix);

    return 0;
}
array.cC / 68 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"

void array_init(struct array *p, int capacity)
{
    p->a = malloc(capacity * sizeof(*p->a));
    p->capacity = capacity;
    p->size = 0;
}

void array_push(struct array *p, int val)
{
    int i;

    for (i = 0; i < p->size; i++)
        if (p->a[i] == val)
            return;

    if (p->capacity == p->size) {
        p->capacity *= 2;
        p->a = realloc(p->a, p->capacity * sizeof(*p->a));
    }

    p->a[p->size] = val;
    p->size++;
}

void array_pop(struct array *p, int *val)
{
    p->size--;
    *val = p->a[p->size];
}

void array_clean(struct array *p)
{
    free(p->a);
    p->capacity = 0;
    p->size = 0;
}

void array_print(struct array p)
{
    int i;

    for (i = 0; i < p.size; i++)
        printf("%d ", p.a[i]);
    printf("\n");
}

void array_copy(int *dst, const int *src, int n)
{
    int i;
    for (i = 0; i < n; i++)
        dst[i] = src[i];
}

int array_compare(const int *a, const int *b, int n)
{
    int i;

    for (i = 0; i < n && a[i] == b[i]; i++)
        {}
    if (i == n)
        return 0;
    return a[i] < b[i] ? -1 : 1;
}
array.hC / 19 lines
#ifndef ARRAY_H
#define ARRAY_H

struct array {
    int *a;
    int size;
    int capacity;
};

void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
void array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);

void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);

#endif
dna.cC / 16 lines
#include <stdlib.h>

#include "dna.h"

static int random_number(double limit)
{
    return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}

void dna_generate(int *a, int n)
{
    int i;

    for (i = 0; i < n; i++)
        a[i] = random_number(DIFF_DNA);
}
dna.hC / 12 lines
#ifndef DNA_H
#define DNA_H

#define DIFF_DNA 4.0

enum {
    dna_len = 100000
};

void dna_generate(int *a, int n);

#endif
dna_apl_test.cC / 32 lines
#include <stdlib.h>
#include <time.h>

#include "array.h"
#include "apl.h"
#include "dna.h"

int main()
{
    struct array res;
    int *dna;
    int (*matrix)[cols];
    int len = dna_len;
    int rows = len - min + 1;

    dna = malloc(len * sizeof(*dna));
    matrix = malloc(rows * sizeof(*matrix));

    srand(time(NULL));

    dna_generate(dna, dna_len);

    matrix_create(dna, len, matrix);
    matrix_merge_sort(matrix, 0, rows - 1);

    array_init(&res, 1);
    apl_find_repeating(matrix, rows, &res);
    array_print(res);
    array_clean(&res);

    return 0;
}
dna_fortran_test.cC / 26 lines
#include <stdlib.h>
#include <time.h>

#include "array.h"
#include "fortran.h"
#include "dna.h"

int main()
{
    struct array res;
    int *dna;
    int min = 6;

    dna = malloc(dna_len * sizeof(*dna));

    srand(time(NULL));

    dna_generate(dna, dna_len);

    array_init(&res, 1);
    fortran_find_repeating(dna, dna_len, min, &res);
    array_print(res);
    array_clean(&res);

    return 0;
}
fortran.cC / 20 lines
#include "array.h"

void fortran_find_repeating(int *arr, int len, int min, struct array *res)
{
    int i, j, k, found;
    for (i = 0; i < len - min; i++) {
        for (j = i + 1; j < len - min + 1; j++) {
            found = 1;
            for (k = 0; k < min; k++)
                if (arr[i+k] != arr[j+k]) {
                    found = 0;
                    break;
                }
            if (found) {
                array_push(res, i);
                array_push(res, j);
            }
        }
    }
}
fortran.hC / 8 lines
#ifndef FORTRAN_H
#define FORTRAN_H

#include "array.h"

void fortran_find_repeating(int *arr, int len, int min, struct array *res);

#endif
fortran_test.cC / 22 lines
#include "array.h"
#include "fortran.h"

int main()
{
    struct array res;
    int min = 5;
    int arr[] = {
        8, 3, 5, 7, 2, 4,
        99, 99,
        3, 5, 7, 2, 4,
        10
    };
    int len = sizeof(arr) / sizeof(arr[0]);

    array_init(&res, 1);
    fortran_find_repeating(arr, len, min, &res);
    array_print(res);
    array_clean(&res);

    return 0;
}
matrix.cC / 74 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"
#include "matrix.h"

void matrix_create(int *arr, int len, int (*a)[cols])
{
    int i, j;
    int rows = len - min + 1;

    if (len < min)
        return;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < min; j++)
            a[i][j] = arr[i + j];
        a[i][j] = i;
    }
}

void matrix_print(int (*a)[cols], int rows)
{
    int i, j;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            printf("%3d ", a[i][j]);
        printf("\n");
    }
}

static void matrix_merge(int (*a)[cols], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
    int (*L)[cols] = malloc(n1 * sizeof(*L));
    int (*R)[cols] = malloc(n2 * sizeof(*R));

    for (i = 0; i < n1; i++)
        array_copy(L[i], a[l + i], cols);

    for (j = 0; j < n2; j++)
        array_copy(R[j], a[m + 1 + j], cols);

    for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
        if (array_compare(L[i], R[j], min) <= 0) {
            array_copy(a[k], L[i], cols);
            i++;
        } else {
            array_copy(a[k], R[j], cols);
            j++;
        }

    for (; i < n1; i++, k++)
        array_copy(a[k], L[i], cols);
    for (; j < n2; j++, k++)
        array_copy(a[k], R[j], cols);

    free(L);
    free(R);
}

void matrix_merge_sort(int (*a)[cols], int l, int r)
{
    int m;
    if (l < r) {
        m =  (l + r) / 2;
        matrix_merge_sort(a, l, m);
        matrix_merge_sort(a, m + 1, r);
        matrix_merge(a, l, m, r);
    }
}
matrix.hC / 13 lines
#ifndef MATRIX_H
#define MATRIX_H

enum {
    min = 5,
    cols = min + 1
};

void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);

#endif
merge_sort.cC / 54 lines
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];

    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }

    for (; i < n1; i++, k++)
        arr[k] = L[i];
    for (; j < n2; j++, k++)
        arr[k] = R[j];
}

void merge_sort(int arr[], int l, int r)
{
    int m;
    if (l < r) {
        m =  (l + r) / 2;
        merge_sort(arr, l, m);
        merge_sort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

int main()
{
    int i;
    int arr[] = {38, 27, 43, 10};
    int len = sizeof(arr) / sizeof(*arr);

    merge_sort(arr, 0, len - 1);
    for (i = 0; i < len; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}
Section testlanguages-01 (09-03-01)In catalog
MakefileMake / 24 lines
PROGRAMS = fortran_test apl_test dna_apl_test dna_fortran_test

SRCMODULES = array.c matrix.c apl.c fortran.c dna.c
OBJMODULES = $(SRCMODULES:.c=.o)
HEADERS = $(wildcard *.h)

CC = gcc
CFLAGS = -g -Wall -O2 -ansi -pedantic

.PHONY: all clean

all: $(PROGRAMS) merge_sort

%.o: %.c $(HEADERS)
    $(CC) $(CFLAGS) -c $< -o $@

$(PROGRAMS): %: %.c $(OBJMODULES) $(HEADERS)
    $(CC) $(CFLAGS) $(filter-out %.h,$^) -o $@

merge_sort: merge_sort.c
    $(CC) $(CFLAGS) $< -o $@

clean:
    rm -f *.o $(PROGRAMS) merge_sort
apl.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>

#include "matrix.h"
#include "apl.h"

void apl_find_repeating(int (*a)[cols], int rows, struct array *res)
{
    int i;
    char *seen;

    if (rows < 2)
        return;

    seen = calloc(rows, 1);
    if (!seen) {
        fprintf(stderr, "apl_find_repeating: out of memory\n");
        exit(1);
    }

    for (i = 0; i < rows - 1; i++)
        if (array_compare(a[i], a[i+1], min) == 0) {
            seen[a[i][min]] = 1;
            seen[a[i+1][min]] = 1;
        }

    for (i = 0; i < rows; i++)
        if (seen[i])
            array_push(res, i);

    free(seen);
}
apl.hC / 9 lines
#ifndef APL_H
#define APL_H

#include "array.h"
#include "matrix.h"

void apl_find_repeating(int (*a)[cols], int rows, struct array *res);

#endif
apl_test.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"
#include "matrix.h"
#include "apl.h"

int main()
{
    struct array res;
    int arr[] = {
        8, 3, 5, 7, 2, 4,
        99, 99,
        3, 5, 7, 2, 4,
        10
    };
    int len = sizeof(arr) / sizeof(*arr);
    int rows = len - min + 1;
    int (*matrix)[cols] = malloc(rows * sizeof(*matrix));

    if (!matrix) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    matrix_create(arr, len, matrix);
    matrix_print(matrix, rows);
    printf("\n");
    matrix_merge_sort(matrix, 0, rows - 1);
    matrix_print(matrix, rows);

    array_init(&res, 1);
    apl_find_repeating(matrix, rows, &res);
    array_print(res);
    array_clean(&res);

    free(matrix);

    return 0;
}
array.cC / 81 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"

void array_init(struct array *p, int capacity)
{
    if (capacity < 1)
        capacity = 1;
    p->a = malloc(capacity * sizeof(*p->a));
    if (!p->a) {
        fprintf(stderr, "array_init: out of memory\n");
        exit(1);
    }
    p->capacity = capacity;
    p->size = 0;
}

void array_push(struct array *p, int val)
{
    int *tmp;
    int capacity;

    if (p->capacity == p->size) {
        capacity = p->capacity > 0 ? p->capacity * 2 : 1;
        tmp = realloc(p->a, capacity * sizeof(*p->a));
        if (!tmp) {
            fprintf(stderr, "array_push: out of memory\n");
            exit(1);
        }
        p->a = tmp;
        p->capacity = capacity;
    }

    p->a[p->size] = val;
    p->size++;
}

int array_pop(struct array *p, int *val)
{
    if (p->size == 0)
        return 0;
    p->size--;
    *val = p->a[p->size];
    return 1;
}

void array_clean(struct array *p)
{
    free(p->a);
    p->a = NULL;
    p->capacity = 0;
    p->size = 0;
}

void array_print(struct array p)
{
    int i;

    for (i = 0; i < p.size; i++)
        printf("%d ", p.a[i]);
    printf("\n");
}

void array_copy(int *dst, const int *src, int n)
{
    int i;
    for (i = 0; i < n; i++)
        dst[i] = src[i];
}

int array_compare(const int *a, const int *b, int n)
{
    int i;

    for (i = 0; i < n && a[i] == b[i]; i++)
        {}
    if (i == n)
        return 0;
    return a[i] < b[i] ? -1 : 1;
}
array.hC / 19 lines
#ifndef ARRAY_H
#define ARRAY_H

struct array {
    int *a;
    int size;
    int capacity;
};

void array_init(struct array *p, int capacity);
void array_push(struct array *p, int val);
int array_pop(struct array *p, int *val);
void array_clean(struct array *p);
void array_print(struct array p);

void array_copy(int *dst, const int *src, int n);
int array_compare(const int *a, const int *b, int n);

#endif
dna.cC / 16 lines
#include <stdlib.h>

#include "dna.h"

static int random_number(double limit)
{
    return 1 + (int)(limit * rand() / (RAND_MAX + 1.0));
}

void dna_generate(int *a, int n)
{
    int i;

    for (i = 0; i < n; i++)
        a[i] = random_number(DIFF_DNA);
}
dna.hC / 12 lines
#ifndef DNA_H
#define DNA_H

#define DIFF_DNA 4.0

enum {
    dna_len = 100000
};

void dna_generate(int *a, int n);

#endif
dna_apl_test.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "array.h"
#include "apl.h"
#include "dna.h"

int main()
{
    struct array res;
    int *dna;
    int (*matrix)[cols];
    int len = dna_len;
    int rows = len - min + 1;

    dna = malloc(len * sizeof(*dna));
    matrix = malloc(rows * sizeof(*matrix));
    if (!dna || !matrix) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    srand(time(NULL));

    dna_generate(dna, dna_len);

    matrix_create(dna, len, matrix);
    matrix_merge_sort(matrix, 0, rows - 1);

    array_init(&res, 1);
    apl_find_repeating(matrix, rows, &res);
    array_print(res);
    array_clean(&res);

    free(matrix);
    free(dna);

    return 0;
}
dna_fortran_test.cC / 33 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "array.h"
#include "fortran.h"
#include "matrix.h"  /* min: same window length as the APL version */
#include "dna.h"

int main()
{
    struct array res;
    int *dna;

    dna = malloc(dna_len * sizeof(*dna));
    if (!dna) {
        fprintf(stderr, "out of memory\n");
        return 1;
    }

    srand(time(NULL));

    dna_generate(dna, dna_len);

    array_init(&res, 1);
    fortran_find_repeating(dna, dna_len, min, &res);
    array_print(res);
    array_clean(&res);

    free(dna);

    return 0;
}
fortran.cC / 38 lines
#include <stdio.h>
#include <stdlib.h>

#include "fortran.h"

void fortran_find_repeating(const int *arr, int len, int min, struct array *res)
{
    int i, j, k;
    int nwin = len - min + 1;
    char *seen;

    if (nwin < 2)
        return;

    seen = calloc(nwin, 1);
    if (!seen) {
        fprintf(stderr, "fortran_find_repeating: out of memory\n");
        exit(1);
    }

    for (i = 0; i < len - min; i++) {
        for (j = i + 1; j < len - min + 1; j++) {
            for (k = 0; k < min; k++)
                if (arr[i+k] != arr[j+k])
                    break;
            if (k == min) {
                seen[i] = 1;
                seen[j] = 1;
            }
        }
    }

    for (i = 0; i < nwin; i++)
        if (seen[i])
            array_push(res, i);

    free(seen);
}
fortran.hC / 8 lines
#ifndef FORTRAN_H
#define FORTRAN_H

#include "array.h"

void fortran_find_repeating(const int *arr, int len, int min, struct array *res);

#endif
fortran_test.cC / 22 lines
#include "array.h"
#include "fortran.h"

int main()
{
    struct array res;
    int min = 5;
    int arr[] = {
        8, 3, 5, 7, 2, 4,
        99, 99,
        3, 5, 7, 2, 4,
        10
    };
    int len = sizeof(arr) / sizeof(arr[0]);

    array_init(&res, 1);
    fortran_find_repeating(arr, len, min, &res);
    array_print(res);
    array_clean(&res);

    return 0;
}
matrix.cC / 88 lines
#include <stdio.h>
#include <stdlib.h>

#include "array.h"
#include "matrix.h"

void matrix_create(int *arr, int len, int (*a)[cols])
{
    int i, j;
    int rows = len - min + 1;

    if (len < min)
        return;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < min; j++)
            a[i][j] = arr[i + j];
        a[i][min] = i;
    }
}

void matrix_print(int (*a)[cols], int rows)
{
    int i, j;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            printf("%3d ", a[i][j]);
        printf("\n");
    }
}

static void matrix_merge(int (*a)[cols], int (*tmp)[cols], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
    int (*L)[cols] = tmp;
    int (*R)[cols] = tmp + n1;

    for (i = 0; i < n1; i++)
        array_copy(L[i], a[l + i], cols);

    for (j = 0; j < n2; j++)
        array_copy(R[j], a[m + 1 + j], cols);

    for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
        if (array_compare(L[i], R[j], min) <= 0) {
            array_copy(a[k], L[i], cols);
            i++;
        } else {
            array_copy(a[k], R[j], cols);
            j++;
        }

    for (; i < n1; i++, k++)
        array_copy(a[k], L[i], cols);
    for (; j < n2; j++, k++)
        array_copy(a[k], R[j], cols);
}

static void matrix_merge_sort_rec(int (*a)[cols], int (*tmp)[cols],
                                  int l, int r)
{
    int m;
    if (l < r) {
        m =  (l + r) / 2;
        matrix_merge_sort_rec(a, tmp, l, m);
        matrix_merge_sort_rec(a, tmp, m + 1, r);
        matrix_merge(a, tmp, l, m, r);
    }
}

void matrix_merge_sort(int (*a)[cols], int l, int r)
{
    int (*tmp)[cols];

    if (l >= r)
        return;

    tmp = malloc((r - l + 1) * sizeof(*tmp));
    if (!tmp) {
        fprintf(stderr, "matrix_merge_sort: out of memory\n");
        exit(1);
    }
    matrix_merge_sort_rec(a, tmp, l, r);
    free(tmp);
}
matrix.hC / 13 lines
#ifndef MATRIX_H
#define MATRIX_H

enum {
    min = 5,
    cols = min + 1
};

void matrix_create(int *arr, int len, int (*a)[cols]);
void matrix_print(int (*a)[cols], int rows);
void matrix_merge_sort(int (*a)[cols], int l, int r);

#endif
merge_sort.cC / 71 lines
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int tmp[], int l, int m, int r)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
    int *L = tmp;
    int *R = tmp + n1;

    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    for (i = 0, j = 0, k = l; i < n1 && j < n2; k++)
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }

    for (; i < n1; i++, k++)
        arr[k] = L[i];
    for (; j < n2; j++, k++)
        arr[k] = R[j];
}

void merge_sort_rec(int arr[], int tmp[], int l, int r)
{
    int m;
    if (l < r) {
        m =  (l + r) / 2;
        merge_sort_rec(arr, tmp, l, m);
        merge_sort_rec(arr, tmp, m + 1, r);
        merge(arr, tmp, l, m, r);
    }
}

void merge_sort(int arr[], int l, int r)
{
    int *tmp;

    if (l >= r)
        return;

    tmp = malloc((r - l + 1) * sizeof(*tmp));
    if (!tmp) {
        fprintf(stderr, "merge_sort: out of memory\n");
        exit(1);
    }
    merge_sort_rec(arr, tmp, l, r);
    free(tmp);
}

int main()
{
    int i;
    int arr[] = {38, 27, 43, 10};
    int len = sizeof(arr) / sizeof(*arr);

    merge_sort(arr, 0, len - 1);
    for (i = 0; i < len; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

9.3.2 C and Pascal: a conceptual difference

C makes assignment and other effects part of expressions, whereas Pascal more visibly separates actions from calculated values. Input loops can benefit from combined retrieval and testing, but compact idioms can obscure effects such as process creation.

Both functions copy a string. The first uses the classic C idiom, in which the loop condition does all the work through side effects; the second keeps the condition free of them:

void wrong(char *dest, const char *src)
{
    while ((*dest++ = *src++));
}

void correct(char *dest, const char *src)
{
    for (; *src; src++, dest++)
        *dest = *src;
    *dest = 0;
}

Pascal expressions cannot change variables, so only the second form exists there:

program loop_side_effects_pas;

procedure correct(var dest: string; src: string);
var
    i: integer;
begin
    SetLength(dest, length(src));
    for i := 1 to length(src) do
        dest[i] := src[i]
end;

var
    src, dest: string;
begin
    src := 'hello';
    correct(dest, src);
    writeln(src, ' ', dest)
end.
hello hello
Detailed notes - 9.3.2: C and Pascal: a conceptual difference

1

C and Pascal share many imperative constructs

  • variables, types, assignment, blocks, branches, loops, subprograms
  • notation changes such as braces versus begin/end are superficial
  • language meaning matters more than the printed symbols

2

more substantial differences include:

  • main function versus a distinct main-program block
  • C block-local declarations
  • C character codes as integer values
  • value-only parameter passing with explicit pointer output parameters
  • pointer arithmetic makes array suffixes easy to pass

3

book values C's separation between core syntax and library facilities

  • many services are ordinary function calls rather than special statements

4

many such facilities could be added to another dialect or implementation

  • they do not alone explain the difference in programming habits

5

author identifies treatment of side effects as the central conceptual difference

6

book adopts a narrow, expression-centered definition of side effect

  • distinguishes an action's main purpose from an effect of evaluating a value
  • wider programming literature also calls procedure/statement effects side effects
  • follow the author's terminology when interpreting this comparison

7

within that definition, expression evaluation has a side effect if it changes something observable beyond producing its value

8

C assignment is an expression

  • x = 7 yields a value and changes x
  • x = 7; discards the value and retains the effect

9

Pascal assignment is a statement, not a subexpression

  • author therefore calls its update an action rather than a side effect
  • this distinction is terminological, not a difference in whether state changes

10

Pascal expressions can still call effectful functions

  • sample f prints its argument and returns its square
  • a := f(15) + 2 includes output during right-side evaluation
  • m[f(5)-3] := 7 includes output while selecting a destination

11

Pascal distinguishes procedure calls from value-returning function calls

  • original dialect restricted discarding a function's result
  • later dialects relaxed that restriction
  • author associates the separation with clearer action/value roles

12

C uses functions, including void functions, for both roles

  • machine-level similarity does not eliminate a source-level conceptual difference

13

void call has no result value but can perform effects

  • C's expression-statement model accommodates those effects directly
  • ordinary state-changing actions therefore appear as effectful expressions
  • author argues that this makes side effects seem unremarkable

14

compact copy idiom combines assignment and two pointer increments

  • while((*dest++ = *src++)) {}
  • expanded version separates copy, pointer advances, and final zero
  • same intended transformation, different burden on the reader

15

some loops naturally follow retrieve -> test -> process

  • while(fscanf(stream, "%d", &n) == 1) retrieves inside the condition
  • moving retrieval outside may duplicate the call before/inside the loop
  • result must be checked before processing n

16

another form uses an indefinite loop and an explicit break

  • retrieve once in the body
  • if retrieval failed, break
  • otherwise process and repeat
  • author weighs duplicated code, condition effects, and less visible termination

17

choice among these forms is partly a readability decision

  • condition-side retrieval has a real purpose in this specific loop shape

18

author does not generalize that exception to every effectful condition

  • recommends separating unrelated effects from tests
  • wait(NULL) loops illustrate a case needing closer analysis

19

waiting without per-child processing is action -> test

  • can be written as do { pid = wait(NULL); } while(pid != -1)
  • adding processing after each successful wait changes the loop shape
  • real code must distinguish EINTR from "no children" rather than stop indiscriminately on every wait error

20

array[i++] = value combines storing and advancing

  • author prefers separate statements to expose both steps
  • compact spelling alone does not establish a speed advantage

21

action-oriented functions often return status or another result in C

  • output parameters are an alternative
  • existing C interfaces mix these conventions
  • cannot impose a single stylistic rule by ignoring documented return values

22

book's Pascal rule allows effectful retrieval where it clarifies an input loop

  • otherwise favors explicit procedure actions and effect-free calculations

23

translating that rule to C requires exceptions

  • assignment as a separate statement still has an effect
  • status-returning library functions must have their results handled

24

experience with another language can make a style rule's motivation clearer

  • unexplained prohibitions teach compliance rather than understanding

25

author argues that C makes mixing actions into expressions particularly easy

  • the proposed lesson is to recognize and control that habit

26

this reasoning influenced changes between the book's editions

  • especially its treatment of effectful Pascal functions

27

author strongly prefers alternatives to C for first-language teaching

  • this is his pedagogical conclusion, not a universal verdict on learners

28

fork example exposes the danger of copying syntax without understanding effects

  • fork(); followed by if(fork() == 0) makes additional processes
  • if both forks succeed, four processes reach the following code
  • one initial fork plus two second calls occur across the processes
  • clearer teaching form: pid = fork(); then inspect pid
  • a conditional expression can perform an action as well as compare values

29

an expert may no longer notice the mental model a beginner is missing

  • explain the action and its result, not merely an idiomatic spelling

30

author's closing concern is teaching habits that obscure effects

  • understanding the model should precede imitating concise C idioms
Tests & experiments (9 files) - 9.3.2: C and Pascal: a conceptual difference
Section testPascal-vs-C (09-03-02)In catalog
MakefileMake / 15 lines
PROGRAMS = match loop_side_effects select-check-process wait fork
PROGRAMS_PASCAL = match_pas side_effects loop_side_effects_pas

CFLAGS = -g -Wall -O0 -ansi -pedantic

all: $(PROGRAMS) $(PROGRAMS_PASCAL)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

$(PROGRAMS_PASCAL): %: %.pas
    fpc $^

clean:
    rm -f *.o $(PROGRAMS) $(PROGRAMS_PASCAL)
fork.cC / 30 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

void fork0()
{
    fork();
    if (fork() == 0) {
        sleep(2);
        printf("child\n");
        exit(0);
    }
}


void wait0()
{
    int pid;

    while ((pid = wait(NULL)) != -1)
        printf("%d\n", pid);
}

int main()
{
    fork0();
    wait0();
    return 0;
}
loop_side_effects.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void wrong(char *dest, const char *src)
{
    while ((*dest++ = *src++));
}

void correct(char *dest, const char *src)
{
    for (; *src; src++, dest++)
        *dest = *src;
    *dest = 0;
}

int main()
{
    const char *src = "hello";
    char *dest = malloc(strlen(src) + 1);
    char *dest2 = malloc(strlen(src) + 1);

    wrong(dest, src);
    printf("%s %s\n", src, dest);

    correct(dest2, src);
    printf("%s %s\n", src, dest2);

    free(dest);
    free(dest2);
    return 0;
}
loop_side_effects_pas.pasPascal / 18 lines
program loop_side_effects_pas;

procedure correct(var dest: string; src: string);
var
    i: integer;
begin
    SetLength(dest, length(src));
    for i := 1 to length(src) do
        dest[i] := src[i]
end;

var
    src, dest: string;
begin
    src := 'hello';
    correct(dest, src);
    writeln(src, ' ', dest)
end.
match.cC / 24 lines
#include <stdio.h>

int match(const char *p, const char *s)
{
    switch (*p) {
        case 0:
            return *s == 0;
        case '*':
            return match(p + 1, s) || (*s && match(p, s + 1));
        default:
            return *s && (*s == *p || *p == '?') ? match(p + 1, s + 1) : 0;
    }
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: %s pattern string\n", argv[0]);
        return 1;
    }
    puts(match(argv[1], argv[2]) ? "yes" : "no");

    return 0;
}
match_pas.pasPascal / 30 lines
program match;

function MatchIdx(var p, s: string; i, j: integer): boolean;
begin
    if i > length(p) then
        MatchIdx := j > length(s)
    else if p[i] = '*' then
        MatchIdx := MatchIdx(p, s, i + 1, j) or
            ((j <= length(s)) and MatchIdx(p, s, i, j + 1))
    else if (j <= length(s)) and ((s[j] = p[i]) or (p[i] = '?')) then
        MatchIdx := MatchIdx(p, s, i + 1, j + 1)
    else
        MatchIdx := false
end;

function Match(p, s: string): boolean;
begin
    Match := MatchIdx(p, s, 1, 1)
end;

begin
    if ParamCount <> 2 then begin
        writeln(ErrOutput, 'usage: ', ParamStr(0), ' pattern string');
        halt(2)
    end;
    if Match(ParamStr(1), ParamStr(2)) then
        writeln('yes')
    else
        writeln('no')
end.
select-check-process.cC / 65 lines
#include <stdio.h>

void process(FILE *f)
{
    int n, sum = 0, count = 0, has_file_ended;

    while (1 == fscanf(f, "%d", &n)) {
        sum += n;
        count++;
    }
    has_file_ended = feof(f);
    if (!has_file_ended)
        fprintf(stderr, "stopped at invalid input\n");
    printf("count: %d, sum: %d\n", count, sum);
}

void process1(FILE *f)
{
    int n, sum = 0, count = 0, has_file_ended, res;

    res = fscanf(f, "%d", &n);
    while (res == 1) {
        sum += n;
        count++;
        res = fscanf(f, "%d", &n);
    }
    has_file_ended = feof(f);
    if (!has_file_ended)
        fprintf(stderr, "stopped at invalid input\n");
    printf("count: %d, sum: %d\n", count, sum);
}

void process2(FILE *f)
{
    int n, sum = 0, count = 0, has_file_ended, res;

    while (1) {
        res = fscanf(f, "%d", &n);
        if (res != 1)
            break;
        sum += n;
        count++;
    }
    has_file_ended = feof(f);
    if (!has_file_ended)
        fprintf(stderr, "stopped at invalid input\n");
    printf("count: %d, sum: %d\n", count, sum);
}

int main(int argc, char **argv)
{
    FILE *f = stdin;

    if (argc > 1) {
        f = fopen(argv[1], "r");
        if (!f) {
            perror(argv[1]);
            return 1;
        }
    }
    process2(f);
    if (f != stdin)
        fclose(f);
    return 0;
}
side_effects.pasPascal / 15 lines
program side;

function f(x: integer) : integer;
begin
    writeln(x);
    f := x * x
end;

var
    a: integer;
    m: array [1..100] of integer;
begin
    a := f(15) + 2;
    m[f(5) - 3] := 7
end.
wait.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/wait.h>

void wait0()
{
    while (wait(NULL) != -1)
        {}
}

void wait1()
{
    while (~wait(NULL));
}

void wait2()
{
    int pid;

    do {
        pid = wait(NULL);
    } while (pid != -1);
}

int main()
{
    int pid;

    pid = fork();
    if (pid == 0) {
        sleep(2);
        printf("finished child\n");
        exit(0);
    }
    wait2();
    printf("finished parent\n");

    return 0;
}

9.3.3 Two ways of comparing languages

Languages can be compared as delivery tools or as notations for expressing solutions. Concise source matters alongside debugging, dependencies, deployment, and the target environment; neither viewpoint alone answers every practical choice.

Detailed notes - 9.3.3: Two ways of comparing languages

1

many languages exist, but no single best language serves every purpose

  • author's broad dissatisfaction frames the following comparison

2

two perspectives emphasize different criteria

  • language as a practical delivery tool
  • language as a notation for expressing knowledge/solutions

3

tool-centered view includes the implementation and deployment environment

  • writing, debugging, packaging, installing, running, and maintaining
  • goal: make the user's system perform the required task

4

notation-centered view emphasizes expressing the solution itself

  • may temporarily abstract from installation/runtime details
  • those details still have to be handled when delivering a real application

5

author warns against confusing abstraction with lack of understanding

  • not thinking about machine details in one task differs from never learning them

6

concise source is only one comparison criterion

  • execution strategy, dependencies, and target environment can matter too
  • neither brevity nor language name alone establishes suitability

7

author prefers tools that impose few requirements on the end user

  • treats deployment/runtime dependencies as part of language choice
  • this is an engineering preference to weigh against actual constraints

8

later chapter examines compilation and interpretation as mental models

  • abstract notation-only comparison can be useful in some contexts
  • it is not enough for every practical decision

9.4 Examples of local paradigms

Treating a condition as a value simplifies boolean results and exposes a small but useful mental model. Explicit comparisons remain clearer when a function's result carries meaning beyond true or false.

Detailed notes - 9.4: Examples of local paradigms

1

condition can itself be a computed value

  • return a == b; replaces an if returning 1 or 0
  • a boolean flag can be tested directly
  • complex conditions can be named by a function
  • understanding this is more important than memorizing a shorter spelling

2

explicit comparison remains useful when zero is a nonboolean result

  • strcmp(...) == 0 clearly denotes equality
  • its sign has meaning beyond simply true/false

3

"condition as value" is a small but consequential mental model

  • broader paradigms contain many such local models
Tests & experiments (2 files) - 9.4: Examples of local paradigms
Section test04 (09)In catalog
MakefileMake / 11 lines
PROGRAMS = paradigms

CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
paradigms.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>

int is_equal_bad(int a, int b)
{
    if (a == b)
        return 1;
    else
        return 0;
}

int is_equal_good(int a, int b)
{
    return a == b;
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: %s <number 1> <number 2>\n", argv[0]);
        return 1;
    }
    puts(is_equal_good(atoi(argv[1]), atoi(argv[2])) ? "yes" : "no");
    return 0;
}

9.4.1 Callbacks

A callback supplies behavior for another component to invoke under its own timing and ordering rules. User data can preserve client state, but the interface must also define lifetimes and when callbacks may occur.

Detailed notes - 9.4.1: Callbacks

1

callback supplies behavior for another subsystem to invoke

  • service may complete later, through a deep call chain, or for many items
  • avoids requiring one immediate result at the original call site

2

client gives the service a function to call when appropriate

  • pass received data or each found item through callback parameters
  • void* user data can identify the client's per-operation state
  • define lifetime and invocation rules as part of the interface

3

callbacks change how control flow is perceived

  • client cannot assume every action happens in its own linear sequence
  • timing, ordering, and count follow the service's documented behavior

4

practice with higher-order functions or event systems can make this model familiar

  • callbacks are not inherently mysterious just because control is indirect

5

client/server roles also exist inside one program

  • one component requests a service; another provides it
  • networked machines are not required for that relationship
The application describes an action now; an event source invokes it later.
A callback separates registration from invocation. Open full size - Editable SVG

9.4.2 Programming with explicit states

Explicit-state programming stores progress between short steps instead of preserving it inside a blocking call. An external driver supplies events or advance requests, letting a parser, traversal, or GUI resume without monopolizing the event loop.

Etude 9.07 matches wildcards without recursion. The state is explicit: the position after the last *, and where in the string that star's current attempt began. On a mismatch, the matcher returns to that state and lets the star take one more character:

#include <stdio.h>

int match(const char *pat, const char *str)
{
    const char *star_loc = NULL;
    const char *str_save = NULL;

    while (*str) {
        if (*pat == '*') {
            star_loc = pat;
            pat = star_loc + 1;
            str_save = str;
        } else if (*str == *pat || *pat == '?') {
            pat++;
            str++;
        } else if (star_loc) {
            pat = star_loc + 1;
            str_save++;
            str = str_save;
        } else {
            return 0;
        }
    }
    while (*pat == '*')
        pat++;

    return *pat == 0;
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <pattern> <string>\n", argv[0]);
        return 1;
    }

    if (match(argv[1], argv[2]))
        printf("matched\n");
    else
        printf("does not match\n");

    return 0;
}
matched
Detailed notes - 9.4.2: Programming with explicit states

1

GUI libraries can hide the main event loop

  • application appears as separate event handlers
  • loop is the service; handlers are callbacks
  • merely recognizing the hidden loop is not enough for responsiveness

2

long handlers make other work wait

  • GUI appears frozen; server clients may time out
  • more CPU power does not remove every source of delay

3

handler must return within the application's response-time budget

  • potentially long blocking operations stall a single-threaded event loop
  • use nonblocking work, resumable steps, or a separate worker as appropriate

4

explicit-state programming represents progress between events

  • finite-state machines are one instance of a broader state-machine model

5

explicit states also arise outside interactive event loops

  • iterative tree traversal stored the work that recursion kept implicitly

6

state representation replaces saved execution position

  • tree example stores active nodes and whether their subtrees were processed
  • state records what remains to be done when execution resumes

7

book's strict step model performs one transition at a time

  • remove switch fallthrough from the traversal to follow that convention
  • this changes organization, not the traversal's result

8

state-machine style is an imperative model with explicit transition rules

  • define what constitutes state and how an event changes it
  • state may be richer than a finite enum

9

represent state as one coherent set of data

  • one enum, a structure, or a connected collection of objects
  • cohesion should be visible to the programmer

10

divide operation into clearly separated steps

  • external caller/event requests each step
  • inputs can be characters, timer events, or explicit advance requests
  • steps need not involve waiting for real-world events

11

step can update state and produce output actions

  • in this model it does not recursively request its own next step
  • event acquisition remains outside the state machine
  • a parser is fed characters rather than blocking to read them internally

12

next action depends on the current state and the supplied event

13

caller need not run the machine continuously in a loop

  • resumable tree traversal can return one value per request
  • retained state permits a later request to continue where it stopped
A byte stream can end a read anywhere, including in the middle of one logical message.
Explicit state turns chunks into complete lines. Open full size - Editable SVG
Tests & experiments (2 files) - 9.4.2: Programming with explicit states
Section test02 (09-04)In catalog
MakefileMake / 11 lines
PROGRAMS = keys

CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
keys.cC / 103 lines
#include <stdio.h>
#include <stdlib.h>

struct node {
    int key;
    struct node *left, *right;
};

static void insert(struct node **p, int key)
{
    while (*p)
        p = key < (*p)->key ? &(*p)->left : &(*p)->right;
    *p = malloc(sizeof(**p));
    if (!*p) {
        perror("malloc");
        exit(1);
    }
    (*p)->key = key;
    (*p)->left = NULL;
    (*p)->right = NULL;
}

static void destroy(struct node *t)
{
    if (!t)
        return;
    destroy(t->left);
    destroy(t->right);
    free(t);
}

/* automaton: in-order walk, one key per step */
enum { max_depth = 64 };

struct walker {
    const struct node *stack[max_depth];
    int top;
};

static void push_left(struct walker *w, const struct node *t)
{
    for (; t && w->top < max_depth; t = t->left) {
        w->stack[w->top] = t;
        w->top++;
    }
}

static void walker_init(struct walker *w, const struct node *root)
{
    w->top = 0;
    push_left(w, root);
}

/* no side effects: only looks at the state */
static int walker_empty(const struct walker *w)
{
    return w->top == 0;
}

/* one step: returns the next key; call only if !walker_empty(w) */
static int walker_next(struct walker *w)
{
    const struct node *t;

    w->top--;
    t = w->stack[w->top];
    push_left(w, t->right);
    return t->key;
}

/* pretend a network client asks for a key */
static void serve_client(struct walker *w, const char *name)
{
    int key;

    if (walker_empty(w)) {
        printf("%s: no keys left\n", name);
        return;
    }
    key = walker_next(w);
    printf("%s gets key %d\n", name, key);
}

int main(void)
{
    int keys[] = { 50, 20, 70, 10, 30 };
    struct node *t = NULL;
    struct walker w;
    size_t i;

    for (i = 0; i < sizeof(keys) / sizeof(*keys); i++)
        insert(&t, keys[i]);
    walker_init(&w, t);
    serve_client(&w, "alice");
    printf("... other work, time passes ...\n");
    serve_client(&w, "bob");
    serve_client(&w, "carol");
    printf("... more work ...\n");
    for (i = 0; i < 3; i++)
        serve_client(&w, "dave");
    destroy(t);
    return 0;
}

9.4.3 Metaprogramming

Metaprogramming generates or manipulates program code, adding a second level of reasoning about what the generated program will do. Macros and C++ templates provide examples with different expressive capabilities.

Detailed notes - 9.4.3: Metaprogramming

1

metaprogramming writes code that produces or manipulates program code

  • analogous to metadata describing data or a metalanguage describing languages

2

a generator can produce another program or one module of it

  • generated code then performs the original task

3

macros are an earlier example of this idea

  • macro definition produces source fragments during expansion
  • C preprocessing is limited compared with more capable macro languages
  • NASM macro repetition supports richer compile-time generation

4

C++ templates and later interpreted-language facilities extend the examples

  • reason about both the generator and the program it produces
  • that additional level of reasoning makes metaprogramming a paradigm
The generator runs to produce a program; the generated program runs to solve the task.
Metaprogramming has two separate executions. Open full size - Editable SVG

Previous: Inside the Kernel Reading map Next: C++ Programming

Comments

Leave a comment Sign in All comments