Package

purescript-rebus

Repository
afcondon/purescript-rebus
License
MIT
Uploaded by
pacchettibotti
Published on
2026-11-28T09:37:46Z

Identity without a name.

Rebus is a tiny PureScript library that gives a visually mnemonic identity to data that is otherwise hard to confirm, by eye, as being the same data — while keeping a typeable text form and a speakable one, so the identity survives a filename, a search box and a screen reader.

A rebus is a deterministic map from content to a memorable pictographic identity: an ordered run of one to five coloured icons — red cow, blue star — together with a typeable hyphenated alias, cow-ambulance.

Five rebuses: a chord progression and the same progression again, both bug-dog; the same progression with one note changed, spider-cat; project 160 as hammer-bus-dragon; a session as lock-music-cube

Two identical progressions land on one picture, which is deduplication for nothing. Change a single note and it avalanches to a different one. That strip is generated by the library itself (make strip), not drawn by hand.

rebusOf (Chords [[42,61,66,70,78],[46,58,65,72,74,79]])
  == { icons: [ { icon: "bug", color: "hsl(188, 62%, 32%)" }
              , { icon: "dog", color: "hsl(214, 62%, 44%)" } ]
     , alias: "bug-dog"
     }

rebusOfTextWidth Three "marginalia:160"     -- three icons, for a set of hundreds

See it

rebus.hylograph.net — the demo, live.

demo/index.html is a single self-contained page: three captured chord progressions of which two are the same take (find the pair by reading the note numbers, then look at the pictures), a live content → glyph → alias → spoken phrase workbench at every width, the collision table measured in the page over 289 ids, and the whole deck.

make demo        # bundles output/Rebus, then open demo/index.html

It draws with the library itself — output/Rebus bundled by esbuild — and not with a JS re-implementation of the hash, because a demo that can silently disagree with the thing it demonstrates is worse than no demo. The icons are the same vendored FontAwesome shapes Quadrat draws, for the same reason.

It has to be served, not pasted into this file: GitHub's markdown sanitiser strips <script>, <style>, <link> and inline style attributes, so a page that computes its glyphs has nothing left on a README. That is what docs/glyph-strip.svg above is for — the same identities, computed by the same library at build time, as a picture that survives.

What it is for

A thing worth keeping usually arrives mid-flow, when stopping to invent a name is exactly the wrong demand. But a pile of anonymous captures is unusable, because nothing in it can be recognised, referred to, or typed. Rebus dissolves that tension: every capture gets an identity derived from its own content, immediately and for free, and naming becomes a later, optional promotion rather than a toll on the way in.

Two halves, answering different questions:

  • content → icon shapes. One weakly-independent hash per position picks an ordered run from the deck. Identical content lands on the identical run, which gives deduplication for nothing; a real edit avalanches to a visibly different run. Runs rather than singles because an absurd juxtaposition (cow-ambulance, star-bomb) is far more memorable than any lone icon — and because 64 icons are only 64 identities, which is nothing.
  • icon name → colour. Each icon's colour is a hash of its own name, so cow is always red and star always blue. This is what makes the alias lossless: a rebus reconstructed from the typed characters of "cow-ambulance" renders identically to one computed live from the content.

How wide? Count the things you must tell apart

Width is arithmetic, not taste. A rebus is only an identity if no two of the things it distinguishes collide, so the number of icons follows from how many things that is — measured, here, over the 289 live project ids in Marginalia:

width identities colliding groups over 289 ids
1 64 36
2 4,032 20
3 249,984 0
4 15.2M 0
5 915M 0

The width-2 result is not a bad hash. Even a perfect hash expects about ten collisions putting 289 items into 4,032 buckets — the birthday problem, and it arrives far earlier than intuition says. So:

  • dozens of things → Two. This is what the pair was designed for: a machine's handful of parked captures, a session's takes.
  • hundreds to a few thousand → Three.
  • more → Four or Five, and think about whether the thing really needs one identity space.

Five is the ceiling, deliberately. Past four the mnemonic stops being one absurd image and becomes a list to recite, and the alias stops being typeable: cow-ambulance-anchor-spider-tornado is thirty-five characters, which nobody is putting in a filename or a pattern by hand.

Width is a closed type, data Width = One | Two | Three | Four | Five, with widthToInt and widthFromInt :: Int -> Maybe Width — not a clamped Int, because there is no meaning for a width of 0 or 6 and silently clamping one would mint identities at a width the caller never asked for.

Position k always reads hash seed k, so a wider rebus extends a narrower one's prefix rather than displacing it: cow-ambulance at width two is the first two icons of the same content at width three. That is what made appending two seeds for widths four and five a safe change rather than a migration.

Sequential integer ids are this hash's worst input

The twenty width-2 collisions above are not scattered; they cluster at a fixed offset of 45 — 160/205, 161/206, 162/207, and so on. That is the signature of a multiplicative hash over short decimal strings that differ in one digit, and namespacing the input does not help: "marginalia:160" and "marginalia:205" collide exactly as "160" and "205" do. Measured, not assumed.

The answer is more icons, not a cleverer input string. Do not spend an afternoon on the string.

Content identity vs durable identity

Rebus is used two ways. They share every line of machinery and they want opposite things, so a caller has to know which one it is choosing — conflating them is a silent bug, not a compile error.

Content identity. The glyph is meant to change when the content changes. Hash what the thing is: the canonical text of a chord progression, a printed patch, a captured sequence. Two identical captures land on one glyph, which is deduplication for free, and a real edit avalanches to a visibly different picture — which is the whole of the "you have changed this since you parked it" indicator. Vetula relies on exactly this.

Durable identity. The glyph is pinned to the thing and must never change. Hash an immutable key: a database id, a UUID, a content hash minted once. The thing gets renamed, moved, re-homed, re-described, and its picture is the one constant a human can still recognise it by. Marginalia uses this — a project's id is the only thing about it that survives everything else.

The trap is one line long. A caller reaching for durable identity and hashing the project's name gets a glyph that changes on rename, which destroys the entire point, and nothing will report it: both calls typecheck, both return a perfectly good rebus, and the damage only shows up the day somebody renames something and their picture is gone.

So: content identity hashes what the thing is; durable identity hashes what the thing is keyed by. If you can edit the input in the UI, it is not a durable key.

The canonical-text contract

Rebus hashes a string, and that is a constraint, not an implementation detail.

The point of a rebus is that two independent programs, with no shared code path, agree on the identity of the same content — the sequencer that captured a chord progression and the sampler that later recalls it must draw the same icons, or the identity is worthless. That agreement is only checkable if the thing being hashed is a readable string someone can print from either side and compare by eye. A class Hashable a where hash :: a -> Int would let the two disagree invisibly.

So the entry point is a class that produces text:

class Canonical a where
  canonical :: a -> String

rebusOf     :: forall a. Canonical a => a -> Glyph
rebusOfText :: String -> Glyph   -- for callers already holding canonical text

An instance is a promise about a serialisation. The one shipped instance, Chords, is fixed by the behaviour of its existing consumers:

canonical (Chords chords) = joinWith " " (map (joinWith "," <<< map show) chords)

That string is the wire format. Sorting the notes, padding them, or changing the separators would re-identify every rebus ever minted from a progression.

Which is why the normalisation lives in a constructor rather than in the instance. A chord's notes have no inherent order — a voicing engine hands them over bass-first, a MIDI capture in the order the fingers landed, a printer ascending — and three honest programs would mint three pictures for one chord. chordsOf sorts each chord and leaves the progression's own order alone:

chordsOf [[61,42,66]] == Chords [[42,61,66]]     -- one chord, one picture
rebusOf (chordsOf a) /= rebusOf (chordsOf (reverse a))   -- backwards is a different piece

Reach for chordsOf whenever two programs have to agree. Use the bare Chords constructor only when the order within a chord is the point — an arpeggio, a strum, a roll — because nothing downstream can tell the two intentions apart afterwards.

There is deliberately no Canonical String instance: claiming that any string is already canonical is exactly the mistake the class exists to prevent. A caller who genuinely holds canonical text says so by calling rebusOfText.

A known set: restricting, choosing, assigning

Everything above deals: content in, identity out, by hash, each thing alone. That is right for an open-ended pile of captures and wrong in three ways for a known, finite set — the node types of a diagram, the parties to a contract — where the pictures are read together and read for meaning. Each has its own module, imported by name; nothing above changed to make room for them.

  1. A hash sometimes says something false. By hash, sunlight is moon-cloud. A reader reads a flame as heat and a skull as danger whether or not anyone meant it, so icons that mean something to a subject are withdrawn from the deck (without) and placed only by declaration (Rebus.Choice).
  2. A hash gives false families. Two unrelated keys that share a cow read as relatives. For a known set the glyphs are assigned (Rebus.Assign): every key is considered with the others and no icon is given to two keys while the deck has icons left.
  3. A subject should look like itself. A Theme is a named part of the default deck; the six of them partition it, so two subjects dealt from different themes cannot share an icon.

Naming the nodes of a diagram by type, within a subject

import Rebus
import Rebus.Assign (assign, assignThemes, glyphOfKey)

-- every subject of the workbench gets a part of the deck of its own
assignThemes [ "build", "energy", "loan", "reinsurance" ]
  -- build: Nature, energy: Animals, loan: Music, reinsurance: Travel

-- one subject's node types, assigned from its theme
types = assign Two (themeDeck Travel)
  [ "deductible", "layer", "party", "programme", "quota share" ]
  -- deductible   map-tractor
  -- layer        compass-truck
  -- party        plane-bus
  -- programme    ambulance-anchor
  -- quota share  rocket-bicycle

glyphOfNode node = glyphOfKey node.type types    -- every deductible wears map-tractor

Dealt by hash from the same deck, those five types share three icons between them (sharedIcons (deal Two (themeDeck Travel) types) names compass, map and tractor), which is three family resemblances nobody intended.

Reserving loaded icons

import Rebus.Choice (Choice(..), chooseAmong, rebusOfChoice)
import Rebus.Assign (assignChoosing)
import Rebus.Parts (memberOf)

-- what means something HERE: the subject's list, not the library's
loaded = [ "fire", "snowflake", "sun", "moon", "bolt", "cloud", "skull", "bomb" ]
names  = without loaded defaultDeck                 -- what names are dealt from

meaning = chooseAmong
  [ { key: "heat", icons: [ "fire" ] }
  , { key: "sunlight", icons: [ "sun" ] }
  ]                                                 -- everything else: Dealt

rebusOfChoice Two names (meaning "heat") "heat"     -- fire, because it was said
rebusOfChoice Two names (meaning "boiler") "boiler" -- two icons, never a loaded one

assignChoosing Two names meaning things             -- the same, over a whole set

memberOf Two names (glyphOfIcons [ "fire" ]) "boiler"
  -- fire, then two dealt icons: the meaning first, the thing's own name after

Choice is Dealt | Chosen (Array String): a choice names icons, not a finished glyph. A glyph's colours are a function of its icon names and nothing else, which is the whole reason a typed alias redraws the same picture; a chosen glyph that brought its own colours would be one its alias could not reproduce. The names are free — an icon withdrawn from the deck, or one drawn specially for oil or money that no deck holds. And the choice is about one thing, so a policy for a subject is an ordinary function thing -> Choice.

What assignment promises

assign width deck keys is a function of the set of keys: the same glyphs whatever order the keys come in. No two keys get the same glyph, nor the same icons in a different order, while the deck has that many combinations. No icon stands in two glyphs while keys × width fits in the deck; past that, icons are reused least-used first, so the most-used and least-used differ by one (by two, where a key had to step off the least-used icons because that set was already another key's). And it agrees with the hash wherever the hash was right: a key alone, the first key in assignOrder, and every key of a set the hash dealt without sharing an icon, get exactly rebusOfWithWidth.

Stability is partial, and has to be. If adding a key could never move another, each key's glyph would depend on that key alone — which is a hash, and a hash shares icons. Full stability and "no icon shared" cannot both hold for a function of the set, and assign keeps "no icon shared". What is left:

Adding a key never changes the glyph of any key that comes before it in assignOrder; a key after it changes only if the newcomer, or a key the newcomer displaced, took one of its icons.

Measured, adding a thirteenth key to twelve pairs from the default deck moves a little under half a key on average, and more as the deck fills. Add treaty to the five types above and one moves: treaty comes before programme in assignOrder and takes its anchor and ambulance.

When an assignment has been shown to someone and must not move at all, store it and grow it with assignMore, which keeps every glyph already given and assigns only the new keys around them. The price is that the result then depends on history, which is why it has to be stored.

For keys that should stay hashed (no table to store, each glyph still the key's own), dealWidening deals the set and gives an extra icon to just the keys that clash: of marginalia:160, :161 and :205 at width two, 160 and 205 become hippo-key-moon and hippo-key-bicycle and 161 stays a pair. clashes and sharedIcons report what a dealt set got wrong.

Two-part names

"First icon the family, second the member": rebusAppend joins two glyphs, memberOf deals the member part from the deck without the family's icons, and assignTwoPart does it for a set — families assigned among themselves from one deck, the members of each family among themselves from another:

assignTwoPart
  { familyWidth: One, familyDeck: themeDeck Animals
  , memberWidth: One, memberDeck: themeDeck Tools }
  [ { family: "party", member: "cedent" }, { family: "party", member: "broker" }
  , { family: "layer", member: "first" }, { family: "layer", member: "second" } ]
  -- every party begins hippo, every layer frog; the second icon is the member's

Where an alias does not read back

Every glyph these modules make is the glyph of its icon names, so the alias spells it and rebusFromAnyAlias redraws it — with three exceptions, all of them about the alias's grammar rather than about decks. More than five icons (a two-part name of three and three) is past the width an alias is read at. An icon name with a hyphen in it reads back as two icons, so do not give a custom icon one. And Chosen [] is a glyph of no icons with the empty alias. The spoken form is not the library's: it is a renderer saying each icon's colour and name, and works for any glyph.

The API of the three modules

-- Rebus.Deck  (re-exported by Rebus)
without      :: Array String -> Deck -> Deck       -- withdraw the named icons
only         :: Array String -> Deck -> Deck       -- keep only the named icons, in deck order
data Theme = Animals | Travel | Nature | Tools | Music | Emblems
allThemes    :: Array Theme
themeName    :: Theme -> String
themeFromName :: String -> Maybe Theme
themeIcons   :: Theme -> Array String
themeOfIcon  :: String -> Maybe Theme
themeDeck    :: Theme -> Deck
themesDeck   :: Array Theme -> Deck

-- Rebus
glyphOfIcons :: Array String -> Glyph              -- icons you name, not dealt
iconNames    :: Glyph -> Array String

-- Rebus.Choice
data Choice = Dealt | Chosen (Array String)
rebusOfChoice :: Width -> Deck -> Choice -> String -> Glyph
chooseAmong   :: forall key. Eq key => Array { key :: key, icons :: Array String } -> key -> Choice
chosenIcons   :: forall thing. (thing -> Choice) -> Array thing -> Array String

-- Rebus.Parts
rebusAppend :: Glyph -> Glyph -> Glyph
memberOf    :: Width -> Deck -> Glyph -> String -> Glyph

-- Rebus.Assign
type Named = { key :: String, glyph :: Glyph }
glyphOfKey     :: String -> Array Named -> Maybe Glyph
assign         :: Width -> Deck -> Array String -> Array Named
assignMore     :: Width -> Deck -> Array Named -> Array String -> Array Named
assignChoosing :: Width -> Deck -> (String -> Choice) -> Array String -> Array Named
assignOrder    :: Array String -> Array String
deal           :: Width -> Deck -> Array String -> Array Named
dealWidening   :: Width -> Deck -> Array String -> Array Named
clashes        :: Array Named -> Array (Array String)
sharedIcons    :: Array Named -> Array { icon :: String, keys :: Array String }
assignTwoPart  :: TwoPart -> Array Membership -> Array NamedMember
assignThemes   :: Array String -> Array { key :: String, theme :: Theme }

A restricted or themed deck is a different identity space like any other deck (see below): the same text deals to a different glyph, and withdrawing one more icon later re-deals everything dealt from it. Decide what is withdrawn once.

Each promise in this section is a law in Test.Rebus.Decks and Test.Rebus.Assign, checked over a sweep of decks, widths and key sets; and a third golden corpus, Test.Rebus.GoldenPinned (750 cases, taken before any of this was written), holds that no existing glyph or alias moved.

The deck is a versioning decision

The icon deck is a value — defaultDeck, with rebusOfWith :: Deck -> String -> Glyph for a deck of your own — but a different deck is a different identity space, not a preference.

An index into the deck is what a content hash actually produces. Reordering an entry, removing one, or inserting in the middle silently re-identifies every rebus ever minted: the alias someone wrote down stops matching the picture they remember. defaultDeck is therefore fixed and append-only — and even appending changes identities, because the hash is reduced modulo the deck size.

Two programs that must agree have to agree on the deck first, and a program that changes its deck has performed a data migration whether or not it migrated anything. They must agree on the width, too, for the same reason and with the same force.

The palette is not like this. A rebus is identified by its icons, which is what the alias records; colour is a memorability accent laid on top. Recolouring is a visual change, not a migration — which is why rebusOfWith takes a deck and no palette.

Colour de-duplication is pairwise: an icon's colour is bumped only when it collides with the colour of the icon immediately before it. The palette holds eight colours and a run can hold five, so all-distinct is not worth chasing — all that is needed is that two icons standing side by side are not mistaken for one shape drawn twice.

Containers, and why a triple

sessionAliasOf yields a triple ("cat-rocket-anchor"), and the difference from a content pair is load-bearing:

  • A container is not its contents. A triple never reads as one of the pairs inside it — a session is not a take, a folder is not a file — and the eye should know that before it reads the words.
  • A container has no content to hash, so the triple is seeded, not derived. It should not dedup with another container that happens to be empty in the same way, and it should not change identity as things are put into it. Mint the seed once, persist the alias, recover the icons with rebusFromAnyAlias.

Consumers conventionally draw a triple monochrome, leaving colour to mean "this is content".

A seeded alias is literally the alias of the rebus of the seed's decimal digits — seededAliasOfWith w d seed = (rebusOfWithWidth w d (show seed)).alias — so a triple and a pair come from one well with one de-duplication rule, rather than from two rules that only look alike.

Renderer-free

Rebus draws nothing. It yields an icon name and a colour string, and mapping those onto FontAwesome classes, SVG symbols, ANSI escapes or a plotter is the consumer's business. There is no Halogen here, no CSS, no icon font — the default deck's names happen to be FontAwesome free-solid names, so the common case needs no lookup table, but nothing in the library knows that.

Glyph carries icons :: Array GlyphIcon rather than named fields, so a renderer draws whatever width it is handed without knowing which it was.

Dependencies are prelude, arrays, strings, maybe. Nothing else.

API

-- Rebus
data Width = One | Two | Three | Four | Five
allWidths    :: Array Width
widthToInt   :: Width -> Int
widthFromInt :: Int -> Maybe Width

type GlyphIcon = { icon :: String, color :: String }
type Glyph     = { icons :: Array GlyphIcon, alias :: String }
type ChipView  = { glyph :: Glyph, diverged :: Boolean }

-- content → identity   (the plain names keep the width they shipped with: two)
rebusOf             :: forall a. Canonical a => a -> Glyph
rebusOfWidth        :: forall a. Canonical a => Width -> a -> Glyph
rebusOfText         :: String -> Glyph
rebusOfTextWidth    :: Width -> String -> Glyph
rebusOfWith         :: Deck -> String -> Glyph
rebusOfWithWidth    :: Width -> Deck -> String -> Glyph

-- alias → identity
rebusFromAlias      :: String -> Glyph            -- fixed at two; see below
rebusFromAliasWidth :: Width -> String -> Glyph
rebusFromAnyAlias   :: String -> Glyph            -- width read off the hyphens

-- seed → identity      (a container, which has no content to hash)
sessionAliasOf      :: Int -> String              -- three
sessionAliasOfWith  :: Deck -> Int -> String
seededAliasOf       :: Width -> Int -> String
seededAliasOfWith   :: Width -> Deck -> Int -> String

-- Rebus.Canonical
class Canonical a where canonical :: a -> String
newtype Chords = Chords (Array (Array Int))
chordsOf :: Array (Array Int) -> Chords

-- Rebus.Deck
newtype Deck    = Deck (Array String)
newtype Palette = Palette (Array String)
defaultDeck    :: Deck
defaultPalette :: Palette
deckIcons      :: Deck -> Array String
deckSize       :: Deck -> Int
paletteColors  :: Palette -> Array String
paletteSize    :: Palette -> Int

import Rebus brings all three modules in.

rebusFromAlias is fixed at two, and that is a compatibility decision rather than a design one: anything that is not exactly two hyphen-separated parts degenerates to the whole string drawn twice, and there are persisted aliases — and goldens — that record exactly that. New code that may meet a wider alias should use rebusFromAnyAlias, which reads the width off the hyphens; a caller that knows what it stored should use rebusFromAliasWidth, which treats the wrong number of parts as the corrupt data it is.

Tests

spago test

Two corpora, and they are not equals.

Test.Rebus.Golden is the arbiter: 63 cases whose expectations are the exact outputs of Triggerfish.Glyph, the implementation this library was extracted from, captured before a line of it was moved. Test.Rebus.GoldenWide is 273 cases at widths one to five, generated mechanically from a run once the library could be wider than a pair.

Between them sit the checks in Test.Rebus.Wide, which are the ones that matter most: that the general API at Two is rebusOfText, that at Three it is sessionAliasOf, that a glyph always has as many distinct icons as its width, that every alias round-trips at every width, and that each width extends the one below it. A golden records a value; these record a relationship, and a relationship is what would break if somebody reordered the hash seeds.

A rebus is a persisted identity: somewhere there is a saved capture whose alias was minted by that code. So a mismatch is never a stale test — if the goldens and the code disagree, the code is wrong. Fix the code; do not re-record the goldens.

Origin

Extracted from Triggerfish.Glyph (2026-09-13), where it was minting identities for captured sequencer states. It is general because the second consumer (Quadrat, naming sample sets) needed the same map and had to agree with the first. It grew from a fixed pair to a width of one to five the same day, because the third consumer (Marginalia, naming projects) has 289 things to tell apart and a pair cannot do it.