Self-delimiting unary fields in a finite-alphabet stream
DefinitionUnaryRecordStreamcoding-theoryformal-verification
A positive symbol increments the length of the open field. A zero completes the field, emits its length and resets the open field to zero. An unfinished field at the end contributes nothing. The canonical representation of a natural number is a run of that many ones followed by zero.
Definition code
import Mathlib set_option autoImplicit false namespace UnaryRecordStream /-- The accumulator keeps the open field and the complete fields in reverse. -/ def step (state : ℕ × List ℕ) (symbol : ℕ) : ℕ × List ℕ := if symbol = 0 then (0, state.1 :: state.2) else (state.1+1,state.2) def fields (symbols : List ℕ) : List ℕ := (symbols.foldl step (0,[])).2.reverse def code (n : ℕ) : List ℕ := List.replicate n 1 ++ [0] def encode (values : List ℕ) : List ℕ := values.flatMap code end UnaryRecordStream
Source
Unary coding with a delimiter and an append-only streaming parser.