
3 Pipelines as Function Composition
3.1 Learning Outcomes
By the end of this chapter, you will:
- Understand the fundamental problem of mutable state in scripts and computational notebooks.
- Grasp the mathematical and practical definition of pure functions (determinism and zero side effects).
- See why every T node is a pure function, and why a pipeline is function composition.
- Write pure helper functions in R and Python that plug into pipeline nodes.
- Understand how decoupling logic into external function files (
functions = [...]) keeps domain logic orchestrator-agnostic.
3.3 Pure Functions: The Mathematical Ideal
In mathematics, a function has a beautiful property: for a given input, it always returns the exact same output. The function \(f(x) = x^2\) does not depend on what you computed earlier, nor does it mutate anything outside itself.
A pure function in programming satisfies two conditions:
- Deterministic: Given the same inputs, it always produces the same output. It depends only on its explicit parameters—never on global variables or hidden state.
- Zero Side Effects: It does not alter anything outside its scope. It does not modify global variables, rewrite files unexpectedly, or mutate input objects in place.
Compare these two functions:
# Impure: secretly depends on a global variable
threshold <- 0
filter_positive <- function(df) {
df[df$value > threshold, ] # What is threshold? Who defined it? When?
}
# Pure: all inputs are explicit
filter_above <- function(df, threshold) {
df[df$value > threshold, ] # Everything required is explicitly passed
}The pure version is predictable. You can test it in isolation, run it in parallel, and reason about it without needing to know what happened elsewhere in the program.
3.4 T Nodes Are Pure Functions
This is not a metaphor. A T pipeline node is, by construction, a pure function:
- Explicit Inputs: Upstream data is passed into the node’s sandbox as named inputs. There is no global environment to accidentally read from.
- Explicit Single Output: A node returns exactly one thing: the artifact written to the Nix store by its serializer. A node cannot secretly alter another node’s output.
- Hermetic Execution: Because Nix runs the node inside a hermetic sandbox with no outside network or filesystem leakage, the execution is guaranteed to be pure.
Look at a concrete example:
p = pipeline {
-- Node 1: Produce data. Pure: inputs = none, output = DataFrame (^ipc)
data_node = rn(
command = <{
data.frame(
x = c(1.0, 2.0, 3.0, 4.0, 5.0),
y = c(0.0, 0.0, 1.0, 1.0, 1.0)
)
}>,
serializer = ^ipc
)
-- Node 2: Fit model. Pure: inputs = data_node (^ipc), output = model (^pmml)
model_node = rn(
command = <{
d <- transform(data_node, y = as.factor(y))
glm(y ~ x, data = d, family = binomial(link = "logit"))
}>,
deserializer = ^ipc,
serializer = ^pmml
)
}
build_pipeline(p)data_node takes no inputs and returns a DataFrame. model_node takes one DataFrame (data_node) and produces a model artifact. Neither can reach outside its sandbox.
Because nodes are pure functions, T can cache them safely: if data_node has not changed, T never re-evaluates it. Furthermore, the declaration order inside pipeline { } does not matter. T infers the execution graph solely from data dependencies.
3.5 A Pipeline Is Function Composition
When you write a pipeline in T, you are composing pure functions:
\[\text{Pipeline} = (f_n \circ \dots \circ f_2 \circ f_1)(\text{data})\]
This is identical to the pipe operator in R (|>) or method chaining in pandas:
# Function composition in R
mtcars |>
filter(am == 1) |>
select(mpg)T elevates this concept to the architectural level. Each step is an explicit, named, cached pure function that can run in any language.
-- Pure R node
raw = rn(command = <{ read.csv("data.csv") }>, serializer = ^ipc)
-- Pure Python node composing on R output
transformed = pyn(
command = <{
transformed = raw.assign(log_val = numpy.log(raw["val"]))
}>,
deserializer = ^ipc,
serializer = ^ipc
)Because both nodes are pure, the serializer/deserializer contract (^ipc) functions as the type signature between them. The underlying runtime is an implementation detail!
3.6 Writing Clean, Pure Helper Functions
The pure function model applies not just to T nodes as a whole, but to the R and Python code you write inside those nodes.
To keep your code reproducible:
- Never mutate inputs in place: Return a new object instead of modifying an existing one.
- Never rely on global variables: Pass all configuration parameters explicitly.
- Isolate file I/O: Separate functions that calculate values from functions that read/write disks.
3.6.1 Decoupling Logic: External Functions
You do not have to write all your computational code inline inside <{ ... }>. In fact, professional projects keep domain logic in plain .R or .py files loaded via the functions parameter, while command = <{ ... }> acts as a thin one-line call:
p = pipeline {
raw = node(
command = read_csv("data/sales.csv"),
serializer = ^ipc
)
cleaned = rn(
command = <{ clean_sales(raw) }>,
functions = ["src/utils.R"],
deserializer = ^ipc,
serializer = ^ipc
)
model = pyn(
command = <{ train_model(cleaned) }>,
functions = ["src/train.py"],
deserializer = ^ipc,
serializer = ^pmml
)
}Notice the tremendous advantage of this approach: src/utils.R and src/train.py carry zero T-specific syntax. They are standard, idiomatic R and Python files containing pure functions. They can be:
- Sourced or imported and debugged interactively in your IDE.
- Tested using standard tools (
pytest,testthat). - Reused by colleagues who do not use T.
T acts purely as the orchestration layer: handling scheduling, caching, sandboxing, and data exchange.
3.7 Hands-On Exercise: Decoupling a Pipeline with External Functions
In this exercise, you will put pure functional design into practice by building a pipeline that decouples its computational logic into standalone external .R and .py function files.
3.7.1 The Objective
Instead of writing multi-line logic inline inside <{ ... }>, you will:
- Scaffold a T project and declare the required R and Python dependencies in
tproject.toml. - Create a pure R helper function in
src/helpers.Rthat filters sentinel values and computes derived columns without side effects. - Write a pure R function in
src/clean.Rthat composessrc/helpers.Rto process an input dataset. - Write a pure Python function in
src/summarize.pythat takes the cleaned DataFrame and returns a summary dictionary. - Orchestrate the workflow in
src/pipeline.tusingcommand = <{ ... }>andfunctions = [...]. - Verify caching and inspect the computed outputs.
3.7.2 Project Layout
By the end of this exercise, your project structure will look like this:
my_project/
├── data/
│ └── weather.csv
├── src/
│ ├── helpers.R # Reusable pure helper functions
│ ├── clean.R # Pure R cleaning function
│ ├── summarize.py # Pure Python aggregation function
│ └── pipeline.t # Declarative T orchestrator
├── tproject.toml
└── flake.nix
3.7.3 Step 1: Initialize the Project and Create a Toy Dataset
If you are starting fresh, initialize a new T project and enter its Nix shell:
nix shell --accept-flake-config github:b-rodrigues/tlang -c t init --project my_project
cd my_project
nix developDeclare the R and Python packages needed for Arrow IPC (^ipc), JSON metadata (^json), and pandas in tproject.toml (if you skip this, t run will prompt you to add them automatically):
[r-dependencies]
packages = ["arrow", "jsonlite"]
[py-dependencies]
packages = ["pandas", "pyarrow"]Next, create a small dataset data/weather.csv:
city,temperature,humidity,rainfall
Luxembourg,18.5,72,2.4
Esch,21.0,65,0.0
Differdange,-99.0,80,12.1
Dudelange,19.2,68,1.0
Wiltz,16.8,85,5.6
(Notice the faulty sensor reading -99.0 for Differdange!)
3.7.4 Step 2: Write Pure Helper Functions in src/helpers.R
Create src/helpers.R. This file will contain pure utility functions with explicit arguments and no global state:
- Define
clean_temperatures(df, min_valid = -40, max_valid = 55)that filtersdfto rows wheretemperatureis betweenmin_validandmax_valid(inclusive), adds atemp_fahrenheitcolumn ((temperature * 9 / 5) + 32), and returns the resulting data frame.
Because clean_temperatures is a pure function, you can source it into an interactive R session or write a unit test with {testthat} without needing T or Nix running!
3.7.5 Step 3: Write the External Pure Functions
Now create the domain functions in standalone .R and .py files.
3.7.5.1 R Node Function: src/clean.R
Define a pure function clean_weather(df) that calls clean_temperatures(df) and returns the rows sorted by temperature descending.
3.7.5.2 Python Node Function: src/summarize.py
Define a pure function summarize_weather(df) (using pandas) that returns a dictionary with keys total_cities (int), avg_temp_c (float), avg_temp_f (float), and total_rainfall (float).
Notice that neither file contains any T-specific code or decorators, and neither depends on global pipeline variable names. They are 100% standard, portable R and Python functions!
3.7.6 Step 4: Orchestrate in src/pipeline.t
Now, link everything together declaratively in src/pipeline.t using command = <{ ... }> and functions = [...]:
raw_weather: ingestdata/weather.csvvianode(command = read_csv("data/weather.csv"), serializer = ^ipc).cleaned_weather: an R node (rn()) callingclean_weather(raw_weather)insidecommand = <{ ... }>, sourcing["src/helpers.R", "src/clean.R"]viafunctions, withdeserializer = ^ipcandserializer = ^ipc.weather_summary: a Python node (pyn()) callingsummarize_weather(cleaned_weather)insidecommand = <{ ... }>, loading["src/summarize.py"]viafunctions, withdeserializer = ^ipcandserializer = ^json.- Execute
build_pipeline(p)and printread_node(p.cleaned_weather)andread_node(p.weather_summary).
When working with an AI coding assistant, enforce this architectural separation by prompting:
“Write a pure helper file
src/helpers.Rand a pure R functionclean_weather(df)insrc/clean.R. Ensure all functions only take explicit arguments with no global state. Then write a pure Python functionsummarize_weather(df)insrc/summarize.py. Finally, connect them insrc/pipeline.tusingfunctions = [...]and one-linecommand = <{ ... }>calls. Keep all domain logic in the standalone R and Python files.”
3.7.7 Step 5: Run, Inspect, and Verify Caching
Run the pipeline:
t run src/pipeline.t- Inspect Artifacts: The
print(read_node(...))calls at the bottom ofsrc/pipeline.tdisplay the 4-row cleaned DataFrame (excluding Differdange) and the summary dictionary (total_cities: 4,avg_temp_c: 18.875,avg_temp_f: 65.975,total_rainfall: 9.). - Verify Caching: Re-run
t run src/pipeline.timmediately without editing any files. T detects that no inputs or source files changed and prints:All nodes were already cached — nothing to build. - Update External Logic: Add
"max_temp_c": float(df["temperature"].max())insidesummarize_weatherinsrc/summarize.pyand re-runt run src/pipeline.t. T rebuilds with the updated file and prints the newmax_temp_c: 21.field inweather_summary.
3.8 Summary
- Mutable state in scripts and notebooks creates fragile, order-dependent code.
- Pure functions are deterministic and side-effect free.
- T nodes are pure functions running in isolated Nix sandboxes.
- A pipeline is a Directed Acyclic Graph of function compositions.
- Writing your analytical code in plain, pure R and Python files keeps your work testable and portable.