The thermometer grows up: Spray's next three steps, in Elixir

September 27, 2026 · ALA · thermometer · LiveView · R4

The first thermometer post ended with an application that reads like its requirements: every literal at the top, every leaf generic. It is a real improvement on the bad version. It is also only the first rung of the ladder in John Spray’s book, and I had it described as more than that.

Here is what that version still does. push_reading/2 takes each reading, calls the offset, catches the result, calls the filter, catches its result and the updated filter, checks whether the sampler produced anything, and so on down the line. Spray’s §1.6.3 thermometer is at exactly this point, and his next sentence names the goal:

The next thing we want to do is get rid of the while loop, get rid of the indenting, and stop handling the data that is being passed from one function to another.

The application doesn’t use the intermediate values. It only moves them. Spray’s view is that this “clutters up the code something awful”, and the same goes for the updated filter and sampler structs the app has to carry from one reading to the next. Their state is still theirs: the filter’s memory lives inside the filter, which is what Spray asks for when he says that passing a running average in on every call “breaks an otherwise good abstraction” (§3.11.2). But carrying the structs is still handling. So a pipe that threads state through the app was never the endpoint.

His next steps, each as a goal:

  1. Build, then run (§1.6.4). The app builds a description of the program; something else runs it. The app never touches the data, and the if around the sampler goes away.
  2. Instances with ports, wired from above (§1.6.5). Each abstraction is instantiated with its configuration and connected to the next through a port whose type is a programming paradigm (here, dataflow).
  3. Several kinds of connection (§1.6.6). A real app composes dataflow and UI and events, and “for the UI part of the composition, the lines … mean ‘display inside’”.

Spray writes these steps in C# with new, which can look like a call for objects. It isn’t. In §3.9 he derives the same thing from procedural code: a struct holds the configuration, two more fields hold the wiring, and state joins the struct when it belongs to that concept. In §3.10 he calls it using “objects as a language feature, not a design philosophy”. Two details of that derivation matter in Elixir. Configuration is set once, because passing it on every call “would also mix the data parameters of the function with the configuration parameters, breaking the Interface Segregation Principle”. And the configuration and wiring “can be immutable. Only instances of abstractions that contain state data are mutable”. Elixir has structs and protocols, so the question is only where the mutable part goes when nothing is mutable.

Below are some ways to take each step in Elixir. They aren’t the only ways. The full code is in ala_variants_elixir/thermometer, one folder per step (1.6.4-chain, 1.6.4-stream, and so on), each runnable with elixir run.exs. The four dataflow versions print the same readings for the same input.

Step 1: build, then run

A protocol and a composition value

The programming paradigm is dataflow, and in Elixir a paradigm’s port is naturally a protocol. A step either emits a result or stays quiet:

defprotocol Step do
  @doc "Returns {:emit, output, step} when it has a result, {:quiet, step} when it does not."
  def push(step, data)
end

The domain abstractions are the same generic ideas as before, now each owning its own state:

defmodule LowPassFilter do
  defstruct [:strength, :last]

  defimpl Step do
    def push(%{strength: k, last: last} = f, v) do
      out = last + (v - last) / k
      {:emit, out, %{f | last: out}}
    end
  end
end

defmodule SampleEvery do
  defstruct [:n, count: 0]

  defimpl Step do
    def push(%{n: n, count: c} = s, v) when c + 1 >= n, do: {:emit, v, %{s | count: 0}}
    def push(%{count: c} = s, _v), do: {:quiet, %{s | count: c + 1}}
  end
end

OffsetAndScale, NumberToString, and Display look the same: a struct of configuration and a push that always emits.

A Chain is the composition value. It lives in the paradigm layer with Step, knows nothing about thermometers, and is the only code that moves data from one step to the next:

defmodule Chain do
  defstruct steps: []
  def new(steps), do: %__MODULE__{steps: steps}

  def run(chain, inputs) do
    Enum.reduce(inputs, chain, fn input, chain ->
      case Step.push(chain, input) do
        {:emit, _, chain} -> chain
        {:quiet, chain} -> chain
      end
    end)
  end

  defimpl Step do
    def push(%Chain{steps: steps} = chain, data), do: flow(steps, data, [], chain)

    defp flow([], data, done, chain), do: {:emit, data, %{chain | steps: Enum.reverse(done)}}

    defp flow([step | rest], data, done, chain) do
      case Step.push(step, data) do
        {:emit, out, step} -> flow(rest, out, [step | done], chain)
        {:quiet, step} -> {:quiet, %{chain | steps: Enum.reverse(done, [step | rest])}}
      end
    end
  end
end

And the application:

defmodule Thermometer do
  def program do
    Chain.new([
      %OffsetAndScale{offset: -200, scale: 0.2},
      %LowPassFilter{strength: 10, last: 40.0},
      %SampleEvery{n: 10},
      %NumberToString{decimals: 1},
      %Display{label: "Temperature: "}
    ])
  end
end

Thermometer.program() |> Chain.run(readings)

Compare it with Spray’s §1.6.4:

program = new ADC(channel=2, batchSize=100)
  .foreach().OffsetAndScale(offset=4, slope=8.3).Filter(strength=10)
  .SampleEvery(15).NumberToString(format="#.#").Display();
program.Run();

The Elixir app now does what his does:

Because Chain implements Step itself, a chain can be a step in a bigger chain. That’s Spray’s answer to recursion across abstractions (§8.1): the abstract concept (Step) sits a layer down, and the concrete parts both provide and accept it.

It’s also the monad pattern, split the way Spray splits it. “Monads are a 2-layer pattern. The two layers correspond roughly with ALA’s application and programming paradigms layers” (§6.1.16). Step is the chaining interface and Chain’s flow/4 is Bind: both sit in Programming Paradigms. The domain abstractions are the library functions, and Thermometer.program/0 is the application that composes them. The if the first post couldn’t get rid of now lives in Bind, which is where Spray says it belongs: “we can put that extra code inside the Compose function instead. This refactoring is essentially what the monad pattern is” (§6.1.2).

One Elixir-specific point. Chain.run/2 returns the updated chain, since nothing mutates. Whoever runs the program keeps that value and passes it back next time. That’s Spray’s program variable, and holding it isn’t handling the data: nothing outside Chain looks inside it.

Streams, the closest thing to Spray’s monads

Spray’s §1.6.4 is literally his monad version, and Elixir’s Stream module is the standard library’s version of that idea: build a lazy description, then run it. Make each domain abstraction a configured stream transformer:

defmodule LowPassFilter do
  def smooth(stream, strength: k, initial: initial),
    do: Stream.scan(stream, initial, fn v, last -> last + (v - last) / k end)
end

defmodule SampleEvery do
  def sample(stream, n), do: stream |> Stream.drop(n - 1) |> Stream.take_every(n)
end

The application reads almost exactly like Spray’s:

program =
  readings
  |> OffsetAndScale.map(offset: -200, scale: 0.2)
  |> LowPassFilter.smooth(strength: 10, initial: 40.0)
  |> SampleEvery.sample(10)
  |> NumberToString.map(decimals: 1)
  |> Display.show(label: "Temperature: ")

Stream.run(program)

Here readings is the source stream, which the composition is given. In the repo it’s a simulated one; on hardware it would be a stream that reads the ADC channel on each pull.

This is still a pipe. What makes it different from the first post’s pipe is that the app pipes stages, not values: the first line builds a description, the last line runs it, and no reading or filter state passes through the app’s hands. The filter’s memory lives in its own scan accumulator.

The costs are the monad costs Spray names. It’s a single paradigm and a single line, and it is pull-driven, so it suits a batch or a source you can iterate, not a LiveView that receives one reading at a time. It also runs once. Spray’s programs are “wired up once at the beginning when the application starts executing, and then all ports are considered infinite steams” (§3.11.3), and he criticises Rx because a finished chain “wont run ever again. It has to be reconstructed” (§3.11.4). A Stream is the same: Stream.run/1 consumes it. The Chain value doesn’t have that problem, because its owner keeps it and feeds it the next reading.

Wrapping Stream.scan inside LowPassFilter is one of the two ways Spray suggests using a monad library inside ALA (§6.3): keep the library’s chaining type on the ports and use its operators inside or between the domain abstractions. “There would be no sense in reinventing that functionality.” The other way is a single generic step configured with a library expression.

Step 2: instances with ports

A chain has one input and one output per step. As soon as one output needs to go to two places (the display, plus a tracker for the day’s high), the composition is a graph, not a line.

A graph value and a runner

The wiring can itself be data: named instances, plus a list of who feeds whom. A small runner delivers each emission along the wires, and anything that reaches an unwired edge comes back to the caller:

defmodule Circuit do
  defstruct parts: %{}, wires: %{}

  def new(parts), do: %__MODULE__{parts: Map.new(parts)}

  def wire(%__MODULE__{} = c, from, to),
    do: %{c | wires: Map.update(c.wires, from, [to], &(&1 ++ [to]))}

  def push(%__MODULE__{} = c, id, data) do
    case Step.push(Map.fetch!(c.parts, id), data) do
      {:quiet, part} ->
        {put_part(c, id, part), []}

      {:emit, out, part} ->
        c = put_part(c, id, part)

        case Map.get(c.wires, id, []) do
          [] ->
            {c, [out]}

          targets ->
            Enum.reduce(targets, {c, []}, fn to, {c, outs} ->
              {c, more} = push(c, to, out)
              {c, outs ++ more}
            end)
        end
    end
  end

  defp put_part(c, id, part), do: %{c | parts: Map.put(c.parts, id, part)}
end

It reuses the same Step domain abstractions, unchanged. The instances and wires in a Circuit are a text form of Spray’s diagram: boxes, then lines. I don’t want to push that parallel too far, but it’s the reason a graph value is attractive. It can be printed, checked for unwired ports, or drawn. Spray’s objection to monads is the reverse of this: their code “builds large object structures full of delegate objects, closure objects and other objects ‘under the covers’”, which “makes monads difficult to understand, trace and debug” (§3.11.3). A Stream or a stack of fns is that kind of structure. A Circuit is plain data. It also keeps creating an instance apart from wiring it, as Spray does, so the code can follow the diagram one line at a time (§6.2.2).

Processes, where the concept really is concurrent

The most literal translation of Spray’s objects is a process per instance, with its output port kept in its state and set by a wiring call from the app:

program = Stage.new(%OffsetAndScale{offset: -200, scale: 0.2})

program
|> Stage.wire_in(Stage.new(%LowPassFilter{strength: 10, last: 40.0}))
|> Stage.wire_in(Stage.new(%SampleEvery{n: 10}))
|> Stage.wire_in(Stage.new(%NumberToString{decimals: 1}))
|> Stage.wire_in(Stage.new(%Display{label: "Temperature: "}))

Stage is a generic GenServer (about 30 lines, in 1.6.5-processes/stage.ex) that holds a Step struct and an output pid. On each pushed value it calls Step.push and forwards any emission to the wired output. It reads almost line for line like Spray’s §1.6.5, and mutable state is natural in a process.

Notice what didn’t change: the Step structs. The same LowPassFilter runs synchronously inside a pure Chain and asynchronously inside a Stage. That’s the reason Spray gives for making ports push by default: “push can be either synchronous or asynchronous, whereas pull can only be synchronous” (§3.11.4), so “the choice of synchronous or asynchronous is deferred until the application user stories are written” (§6.2).

I don’t recommend it as the default, though. The Elixir docs list “code organization by process” as an anti-pattern: processes are for runtime concerns such as concurrency, isolation, and lifecycles, not for structuring code. An offset-and-scale doesn’t need its own process. Where a concept is concurrent (a sensor poller, a timer, a bridge from PubSub), a process with a wired output port is exactly Spray’s model, and the same Step structs can live inside it.

Step 3: several kinds of connection, in LiveView

Spray’s §1.6.6 adds a UI to the thermometer:

program = new ADC(channel=2)...wireIn(temperature = new FloatField());

mainwindow = new Window()
   .wireTo(new Label("Temperture:"))
   .WireTo(temperature);

Two kinds of line meet in one app. The dataflow lines carry readings. The UI lines mean “display inside”. A LiveView already has both, and the parallel is closer than I expected.

HEEx nesting is the “display inside” wiring. Function components are the UI domain abstractions, and the template is the UI half of the diagram:

def render(assigns) do
  ~H"""
  <.window>
    <.label text="Temperature:" />
    <.float_field value={@temperature} />
    <.label text="High:" />
    <.float_field value={@high} />
  </.window>
  """
end

<.window> containing <.label> and <.float_field> is new Window().wireTo(new Label(...)).WireTo(temperature), one line per containment wire.

An assign is where the dataflow lands. @temperature is Spray’s temperature variable. The dataflow wiring writes to it and the UI wiring displays it, so it’s the one name the two paradigms share. Both uses are in the application layer, so it isn’t a hidden contract between peers. Spray’s own caveat still applies: a named connection like this is fine at this size and “won’t scale up”, which is why he treats the diagram as the source.

Keep the page out of the data. It’s tempting to compute the temperature in handle_info and assign it. That puts the app straight back at step 0, handling data. Instead the page holds the program as one assign, and a generic runner pushes each reading in and applies whatever reaches the program’s edge. The last instance in each branch is a sink whose output means “put this in assign key”:

defmodule ToAssign do
  defstruct [:key]

  defimpl Step do
    def push(%{key: key} = s, v), do: {:emit, {:assign, key, v}, s}
  end
end

defmodule CircuitRunner do
  import Phoenix.Component, only: [assign: 3]

  def feed(socket, input, data) do
    {program, outs} = Circuit.push(socket.assigns.program, input, data)

    Enum.reduce(outs, assign(socket, :program, program), fn {:assign, key, value}, socket ->
      assign(socket, key, value)
    end)
  end
end

CircuitRunner knows LiveView and circuits, but nothing about thermometers. It’s an execution model, so in Spray’s layers it sits in Programming Paradigms, below the domain abstractions.

The application is now two wirings and a one-line event handler:

defmodule Thermometer do
  def circuit do
    Circuit.new(
      adc: %OffsetAndScale{offset: -200, scale: 0.2},
      filter: %LowPassFilter{strength: 10, last: 40.0},
      sample: %SampleEvery{n: 10},
      format: %NumberToString{decimals: 1},
      temperature: %ToAssign{key: :temperature},
      high: %Maximum{},
      high_format: %NumberToString{decimals: 1},
      high_temperature: %ToAssign{key: :high}
    )
    |> Circuit.wire(:adc, :filter)
    |> Circuit.wire(:filter, :sample)
    |> Circuit.wire(:sample, :format)
    |> Circuit.wire(:format, :temperature)
    |> Circuit.wire(:sample, :high)
    |> Circuit.wire(:high, :high_format)
    |> Circuit.wire(:high_format, :high_temperature)
  end
end

defmodule ThermometerLive do
  use Phoenix.LiveView
  import Widgets

  def mount(_params, _session, socket),
    do: {:ok, assign(socket, program: Thermometer.circuit(), temperature: "--", high: "--")}

  def handle_info({:adc, reading}, socket),
    do: {:noreply, CircuitRunner.feed(socket, :adc, reading)}

  # render/1 as above
end

Fed the same 30 readings as the other versions, the page renders 40.5 with a high of 40.6. Look at the page: it has no arithmetic, no if, and no name for any intermediate value. handle_info hands the reading to the runner and never sees what comes back.

Two cautions carry over from the first post and from Spray.

Where this leaves things

Spray’s stepGoalSome Elixir waysMain cost
§1.6.3 (the first post)literals at the top, generic leavesa function that calls each leaf in turnthe app handles every value and carries each updated struct
§1.6.4build, then run; app never handles dataa Step protocol plus a Chain and runner; Stream stages plus Stream.runone paradigm, one line
§1.6.5instances with ports, wired from abovea graph value plus a runner; processes where the concept is concurrentthe owner holds one opaque program value
§1.6.6several kinds of connectionHEEx as “display inside” wiring, assigns as landing points, a runner that pushes into assignsassign names are symbolic connections; page-level branches

Scored with the current ala_lint (re-run 2026-09-30), using the layer map each step declares (in the repo’s score.exs):

Stepdefault--strict--super-strict
§1.6.1, the bad version0/F0/F0/F
§1.6.3, the first post100/A100/A50/D
§1.6.4 chain or stream, §1.6.5 circuit or processes, §1.6.6 LiveView100/A100/A100/A

§1.6.3’s gap is R11, and the linter now sees the whole of it: the two nil-guard ifs, and push_reading/2 binding each stage’s output only to pass it to the next stage, which is Spray’s “handling the data”. From §1.6.4 on, none of that remains, and the steps score 100 at every level.

The honest open question is §1.6.6 in general. LiveView gives the UI paradigm its own medium (HEEx), and the circuit handles dataflow, so this example gets there without any processes. Events, state-machine transitions, and wires that mix kinds in one graph are harder. I haven’t built a version I’d recommend yet. The checklist itself now states these goals under R4 and in a new “Past the pipe” section, without requiring any one technique.

← all posts