Decision D040 · accepted; not implemented
Sequence patterns match the end of a sequence; & stays
A record of the language's design, as it stood on 2026-11-18: written for the people who build Diaspar, and kept as it was written. Its code is a sketch, not a program of the site, and an older record may show syntax that a later one changed. It names files of the language's source, which is not public yet.
Status: accepted (2026-11-18, by the author, with every recommendation of the questions below; the spread #[a & xs z] in vector literals is accepted too and is implemented with this decision; the warning of question 7 is an open question). Not implemented. Extends D015. To be implemented after step 1 of the migration wave (variants as values, D010 §3c), which changes the same code of the pattern compilers.
The question
#[a b & rest] takes elements from the start of a sequence. Taking the first element and the one before the last has no pattern: #[a & mid y z] is the error "& must be followed by exactly one pattern". Should patterns reach the end of a sequence, how, and is & the right sign for it?
Decision
Patterns may follow the rest. They match the last elements of the sequence. The sign stays &.
(let [#[first & _ penult _] #[1 2 3 4 5]] #[first penult]) ; #[1 4]
(let [#[a b & mid z] '(1 2 3 4 5)] mid) ; (3 4)
(let [#[& _ last] #[1 2 3]] last) ; 3
(let [#[& init last] #[1 2 3]] init) ; (1 2)
(match (string.split location ":") ; "src/app.dias:12:7"; a path may hold a colon
#[& _ line col] (jump line col)
_ nil)
(match exprs ; a body: statements, then the value
#[] nil
#[& before value] (do (for [e before] (run e)) (result value)))
(match path
#[only] (local only)
#[root & _ name] (member root name) ; two elements or more
#[] nil)
The rules
A sequence pattern is #[p1 … pk] or #[p1 … pk & r s1 … sm], with k and m from zero up.
- One
&at most. Only one part of a sequence may have any length, so the lengths decide which element each pattern takes, and nothing is searched for. - After
&comes the rest, a name or_, and then any number of patterns for the end.& _skips without building anything. - It matches a list or a vector of at least
k + melements; without&, of exactlyk.p1 … pktake the firstkelements,s1 … smthe lastm. No element is taken twice:#[a & _ z]does not match a sequence of one element. - The rest is a list of the elements between, in their order,
()when there are none: for a vector and for a list, as the rest is today. - Names are bound in the order written, as in every pattern, so
(= name)may use a name bound to its left. as: namestays last and binds the whole value as it is:#[first & _ last as: all]. A guard follows the pattern:#[a & mid z] when: (every? mid int?).- Parameter vectors do not change:
&is followed by one parameter, the last positional one, then the labels (D030). That parameter may be a pattern, as now, so the end of the arguments is taken apart there:(defn call [f & #[& args last]] …).
| Pattern | Lengths it matches |
|---|---|
#[a b] |
2 |
#[a & r] |
1 or more |
#[a & r z], #[& r y z], #[a b & r] |
2 or more |
#[& r] |
any |
What a sequence is: lists and vectors
Checked on the evaluator and compiled (2026-11-18): #[…] matches vectors and lists; a string, a map, a set and nil do not match. (range 4) and the result of map match because today they are lists. This proposal keeps that set.
- Not an iterator, a generator or anything
Iterable(D036). The clauses of amatchare tried one after another on the same value, and an iterator can be walked once; it may hold a file; it may have no end. So a pattern on the end of an infinite sequence cannot be written: there is nothing to refuse at compile time or at run time. A program says what it pays:(match (vec it) …),(iter.take it 3). Python'smatchtakes aSequenceand not an iterable for the same reason; its starred assignment takes any iterable and never returns on an infinite one; JavaScript's proposal for[first, ...rest, last]has stood at stage 1 since 2020 over this question (double-ended iterators). - Not a
Rangevalue when D036's ranges arrive: a range may be infinite;(vec r)is the way. (Question 6.) - Not a string. A grapheme is a string of one grapheme (D013), so
#[c]would match"x"and bindcto"x", which matches#[c]again: a function over nested sequences would never reach a leaf. Python leavesstrout of sequence patterns for this.counton a string is also O(n). Strings havestring.starts-with?,string.ends-with?andslice. - Not a map or a set: no order.
Costs
n elements, k patterns before &, m after the rest.
| Vector | List | |
|---|---|---|
| The length test | O(1) | walks k + m cells, never the whole list (review P2) |
| An element at the start | O(1) | walks to it |
| An element at the end | O(1) | one walk to the end of the list |
| The rest, bound, no patterns after it | builds n − k cells |
the list's own tail, shared, O(1) |
| The rest, bound, patterns after it | builds n − k − m cells |
builds n − k − m cells |
The rest as _ |
nothing | nothing |
Measured compiled, 100,000 elements: #[a & more] on a vector 2.9 ms (the list is built, 29 ns an element); #[a & _] on a vector 15 ns; #[a & more] on a list 13 ns; (last xs) on a list 0.2 ms (2 ns an element).
- On a vector,
#[first & _ penult _]is constant time and allocates nothing. - On a list, a pattern for the end walks the list once, as
(last xs)and(count xs)do. The cost is the list's, and the pattern shows it: whatever stands after the rest is at the end. It is not the trap of review P2, where#[x & more], a constant-time question, counted the whole list. - The cost to watch is a bound rest, today as with this proposal: a list of
ncells each time. A loop that takes the last element off with#[& init last]is quadratic, on a vector as on a list, as a loop over(butlast xs)is. A vector used as a stack haspeekandpop, which work in place when the vector is unique (D004).
Why the rest is a list
It is one today: (let [#[a & more] #[1 2 3]] more) is (2 3).
- A loop
(match xs #[x & more] (recur more) …)over a vector is linear: the first step builds a list, the next ones share its tail. With a vector for the rest every step would copy, and the loop would be quadratic. - One type whatever was matched: the type of a rest is "list", as the type of
restis (D013 §5), and a rest parameter& moreis a list too. - No view: slices copy (D026), and nothing in the prelude is lazy (D036). Rust binds a subslice for free because it has borrowed views; C# binds what the type's
Slicegives, a copy for an array.
A vector for the rest of a vector would let #[& init last] shorten a unique vector in place. pop and peek already do that. (Question 2.)
Exhaustiveness
Today the check knows enums only (D015): (match xs #[] 0 #[x] 1) gives no warning and fails on two elements with "match: no clause matched #[1 2]". This proposal does not change it.
A sequence pattern is described by lengths: with f = k + m fixed patterns it covers f exactly, or f and more with &, when its element patterns match anything. Patterns after the rest add nothing to this: #[a & _ z] and #[a b & _] cover the same lengths. So a later check, when inference knows the value is a sequence (D007), looks only at lengths from 0 to the largest f plus one, as Rust does for slices, and names the smallest length missing: "match does not handle a sequence of 2 elements". A clause with a guard counts for nothing, as now. Function clauses are not concerned: parameter vectors do not change.
Diagnostics
error: a sequence pattern has one `&`
= help: only one part of a sequence may have any length; to find an element anywhere, use find or index-of
error: `&` must be followed by a name for the rest, or _
= help: #[a & rest], #[a & _ last]
error: after `&` comes a name or _, not a pattern
= help: #[a & #[b c]] is #[a b c]; to compare the rest, use a guard: #[a & r] when: (= r expected)
error: `& more` is the last positional parameter
= help: take the end apart in its pattern: [a & #[& mid z]]
let: the pattern #[first & _ last] does not match #[1]
= note: expected at least 2 elements, got 1: #[1]
- An explanation names an element at the end by its real index,
at [4]: the value is at hand, and a negative index would suggest(nth xs -1), which D036 forbids. - The reader's help for
..and...becomes "the rest of a sequence is& rest, a skipped middle& _". - A capitalized name after
&is the error of D010 §3c, as anywhere a pattern binds.
Macros, printing, the formatter
- The pattern is data as before: a vector of forms in which
&is a symbol. A macro that walks a pattern reads the forms after the rest as patterns. The IR prints#[a%1 & r%2 z%3]. - The formatter keeps
&and the form after it on one line, as a label and its value. Today it may end a line with&(checked: a parameter vector wider than the limit breaks after&). The highlighter shows&as punctuation.
Does it pay?
Counted in std/, compiler/src and examples/ without tests, 45,000 lines:
| What the code does | Places |
|---|---|
Sequence patterns in let, for, parameters and match |
about 1,100 |
of them a pair, #[a b] |
912 |
of them with a rest, #[a & more] |
4 |
(first xs) / (rest xs) |
718 / 189 |
(last xs) / (butlast xs) |
85 / 41 |
(butlast xs) and (last xs) of one value together: #[& init last] |
25 |
(first xs) and (last xs) together: #[first & _ last] |
10 |
The last two by index, (nth xs (- n 2)) with (nth xs (dec n)): #[& _ y z] |
5 |
The middle, (rest (butlast xs)) |
2 |
- About 45 places would read better, one in 1,000 lines. The author's case, the element before the last, has 5, among them the compiler's own reading of a trailing
as: name(front/expand/patterns.dias) andfile:line:colin the test runner. - The code hardly uses the rest it already has. A sequence pattern is a pair or a triple nine times in ten; a sequence of any length is taken apart with
firstandrest, 900 calls against 4 patterns with&. Part of that is Clojure's habit, part is the cost of a bound rest on a vector. So the new form will be rare, and nobody should expect those 45 places to be rewritten. - What it gives where it is used: the length is checked, where
(last xs)of an empty sequence isniland(nth xs (- n 2))raises; a clause ofmatchsays the whole shape; no index arithmetic. - The price is small: one field in the IR's pattern, two functions in the runtime, about 200 lines with the tests, and seven rules, of which five are today's.
Worth having as the completion of the sequence pattern, where the error "& must be followed by exactly one pattern" stands now. Not urgent: it serves few places, and nothing waits for it.
The sign: & stays
| Spelling | Where | The reader today | For Diaspar |
|---|---|---|---|
[a & rest] |
Clojure, ClojureScript, Janet, Fennel | & is a symbol; nothing changes |
kept |
&rest name |
Common Lisp, Emacs Lisp | a symbol | the same family; D030 has &labels opts |
..rest, .. |
Gleam [a, ..rest], Rust [a, rest @ .., z], C# [a, .. var rest, z] |
.. is reserved, ..rest is not a symbol (D029) |
the best skip, #[first .. penult _]; below |
...rest, ... |
JavaScript, TypeScript, Dart | ... is reserved |
as .., one dot longer |
rest ..., rest... |
Scheme and Racket (after the pattern), Julia, CoffeeScript | rest... is not a symbol |
a sign after its name reads against a prefix language |
*rest |
Python, Ruby | a symbol, as *1 (D017) and * (D022) |
#[a *mid z] already means three elements |
[h | t] |
Erlang, Elixir, Prolog | | is a symbol, unused |
says head and tail; nothing to say for the end |
h :: t, x:xs |
OCaml, F#, Scala, Haskell | not a token | infix, lists only |
xs*, xs @ _* |
Scala | _* is a symbol |
a sign after its name |
(a . rest) |
Scheme, Racket | .rest is an accessor (D029) |
taken |
The real choice is & or ...
- Habit (D039, D009). Models write Clojure in Diaspar, and
[a b & more]is Clojure's, Janet's and Fennel's. Of the 230&in the sources about 200 are in parameter vectors, where every model and every Lisp programmer writes&without thinking; sequence patterns outside the tests have 4. With..each of those is an error first, however good its help. - One sign in three places. Parameters, sequence patterns and the proposed macro clauses use
&;&labelsis its relative...would have to replace all of them, and&labelswould need a new spelling too. - The reader.
&needs nothing...restneeds a reader prefix, as~@x, and a fourth rule for the dot aftera.b,.band(f).b(D029). To readers of Rust, Ruby, Kotlin and Swift..is a range, the literal D036 rejected. - Reading with an end and a skip.
..is better here:#[first .. penult _]against#[first & _ penult _], where the two_mean different things and the reader must know that&takes one form. That form is always a name or_, the formatter keeps the two together, and& _is already the way to say "and more" (#[a b & _]). - Construction (D015: a pattern looks like construction). There is no counterpart today:
#[1 & xs 4]is "undefined name: &". A vector is built from parts withconcat(327 calls, 193 lines with a vector literal inside) or, for syntax, with`(a ~@xs b). Languages with a spread use the sign of their rest (...in JavaScript and Dart,*in Python and Ruby,..in C#). If Diaspar gains a spread in vector literals, it should be#[a & xs b], and&reads there as it does in a pattern. It is a separate decision. (Question 5.) - The cost of a change, if the author prefers
..: 230 tokens in 88 files, about 20 literals"&"in the compiler, the IR's text, about 25 lines of documents; a mechanical rewrite over the lossless reader, as D030's, in the migration wave. The lasting cost is the habit above.
Recommendation: keep &. .. wins one of the criteria, the reading of a skip, which is the rarest use of the sign.
Prior art
Checked against the sources on 2026-11-18 where marked ✓.
| Language | The rest, a skip | Patterns after the rest | The middle is | Matches |
|---|---|---|---|---|
Python match ✓ (PEP 634) |
[first, *mid, last], *_ |
yes; one star, anywhere | a new list | a Sequence, not str, bytes; len first |
| Python assignment (PEP 3132) | first, *mid, last = xs |
yes | a new list | any iterable, walked to its end |
| Ruby ✓ | in [first, *mid, last], * |
yes; one splat. The find pattern [*, x, *] has two and searches |
a new array | arrays, deconstruct |
| Rust ✓ | [first, .., penult, _], [a, mid @ .., z] |
yes; one .. |
a subslice, a view | arrays (lengths checked when compiled) and slices; a Vec through &v[..] |
| C# 11 ✓ | [first, .., penult, _], [a, .. var mid, z] |
yes; one | what the type's range indexer or Slice gives |
types with a count and an indexer |
| Dart 3 ✓ | [a, b, ...rest, c, d], ... |
yes; one | a new list | List |
| Julia 1.9 ✓ | a, b..., c = xs |
yes in assignment, eager; not in function definitions | a vector | iterables |
Racket match ✓ |
(list a mid ... z), (list first _ ... penult _), ..k for k or more |
yes; several ..., greedy |
a list | lists; (vector …) for vectors |
| Mathematica | {first_, ___, penult_, _} |
yes; several, with backtracking | a sequence | lists |
| CoffeeScript | [first, mid..., last] |
yes | an array | arrays |
| JavaScript, TypeScript ✓ | [a, ...rest] |
no: the rest must be last, a syntax error otherwise; proposal-deiter, stage 1 since 2020 | an array | iterables, walked |
| Scala ✓ | case Seq(a, rest*), rest @ _*, _* |
no; the extractor init :+ last |
a Seq |
unapplySeq |
| Clojure | [a b & rest :as all] |
no | a seq | anything nth reads; lengths are not checked |
core.match ✓ |
[a & r], ([a & r] :seq) |
no | a seq | vectors, seqs |
| Janet ✓, Fennel ✓ | [a b & more] |
no | a copy (Janet) | tuples, arrays; tables |
| Gleam ✓ | [first, ..rest], [_, ..]; "prefix" <> rest |
no | the tail | lists; a string's prefix |
| Erlang, Elixir ✓ | [h | t]; <<a, rest::binary>> |
no for lists; no for the end of a string (hello <> " world" is not a valid pattern); a binary's end by a computed size |
the tail | lists, binaries |
| Haskell, OCaml, F# ✓, Elm, Lean ✓, Agda | x : xs, x :: xs; arrays of an exact length ([| a; b |], #[x, y, z]) |
no; view patterns (last -> z), xs :|> x of Data.Sequence, active patterns |
the tail | lists |
| Swift, Kotlin | none; val (a, b) = list |
no |
- Languages over arrays took the end into patterns (Python, Ruby, Rust, C#, Dart, Julia), all with the same rule: one part of any length, anywhere, and fixed patterns on both sides. The sketch is that rule.
- Languages over linked lists did not (Erlang, Elixir, Haskell, OCaml, Gleam, Clojure). There a pattern is a test of a constructor, constant time, compiled into a decision tree, and the end of a list is O(n), left to a function. Diaspar has both kinds behind one pattern, and its lists already answer
count,lastandnthin O(n). - Several rests exist where the pattern language searches: Ruby's find pattern, Racket, Mathematica, Prolog's
append/3. The split is then not decided by the length, so the match is a search with a cost that does not show, and a rule is needed for which split wins. Python, Rust, C#, Dart and Julia allow one.
Rejected alternatives
| Alternative | Why not |
|---|---|
No new syntax: last, peek, take-last, (nth xs (- (count xs) 2)) |
it works, and stays; but it does not check the length, cannot stand in a clause of match without a guard and a let, and the index arithmetic is where (nth xs -2) was wanted |
View patterns, (view last z) (Haskell's (last -> z), Racket's app, F#'s active patterns, Scala's init :+ last) |
a general mechanism, any code in a pattern, opaque to exhaustiveness as a guard is; it checks no length (first and last of one element are the same element), and the element before the last needs a function written for it. It may be decided on its own; this question does not need it |
Several & |
a search, above |
Patterns after & rest in a parameter vector, [a & mid z] (Ruby, CoffeeScript) |
at the call (f 1 2 3 4) nothing shows that the last argument is apart. Python and Kotlin let a parameter after the variadic one be passed by name only, which is what labels are here; JavaScript and Julia forbid it. The rest parameter's own pattern does it (rule 7) |
A pattern after &, #[a & #[b c]] |
it is #[a b c]; a literal, a map or a struct never matches a list. The evaluator accepts it today, the C backend answers "not supported yet": the rule closes that difference. In a parameter vector the rest stays a pattern, matched against the list of arguments |
| The rest of a vector as a vector | above, "Why the rest is a list" |
| A view or a lazy sequence for the rest | a new kind of value that keeps the whole sequence alive; D036 keeps laziness explicit |
#[…] on any Iterable, with an error for an infinite one |
above; an end cannot be known without walking |
An index from the end in patterns or in nth |
D036 |
.. for a skip beside & for a rest |
two signs for one thing |
Implementation sketch
After step 1 of the migration wave. Tests and cases first; the harness runs each case compiled and on the evaluator and compares.
- Cases.
tests/cases/patterns.dias: the examples above over a vector and over a list; the rest is a list in both; the least length (#[a & _ z]against one element);as:, a guard, a pattern nested in a struct pattern and in a map pattern;let,for,loop, a function clause through[a & #[& mid z]].tests/cases/error-let-pattern.dias: too short, and a failing element at the end with its real index. Newtests/cases/error-seq-pattern.diascases for the four errors of the expander.compiler/tests/ir.diasandvalidate.dias:#[a%1 & r%2 z%3]printed, read back, and its locals in scope.compiler/tests/reader.dias: the new help for...compiler/tests/fmt.dias:¬ left at the end of a line. - Expander,
front/expand/patterns.dias(seq-pattern): one&, a name or_after it, then patterns; the errors.front/expand/forms.dias(parameters): the message and its help. - IR,
middle/ir.dias:(PSeq [items variadic pos (suffix default: #[])]). Everything that walksitemsandvariadicwalkssuffixas well:ir/print.dias,ir/read.dias,ir/validate.dias,closure.dias,renumber.dias,assemble.dias,eval/compile.dias(pattern-exprs).middle/analyze.dias(pattern): the forms after the rest becomesuffix. - C backend.
back/lir.dias: a path(PNthBack [path index]), the elementindexfrom the end;ORestgains the number of elements left at the end.back/lower.dias(pattern-parts,explain-checks): the condition is theCSeqof today withn = k + m, so the length test stays a walk ofk + mcells on a list; then the elements at the start, the rest, the elements at the end, in the order written.back/rc.dias,back/emit.dias,back/emit/types.dias,back/emit/state.dias: the new path.runtime/support/patterns.candruntime/diaspar.h:dsp_seq_nth_back(a vector by index; a list in one walk with a pointer that lags) anddsp_seq_restwith the count to leave (a list with nothing after the rest still shares its tail). If several elements at the end of a long list show in a profile, the start of the end is found once: the lastmcells of a list are a list. - Evaluator,
eval/compile.dias(compile-pattern,compile-explain): the count once; the elements at the end by index, for a list after onedrop; the rest as now, less the end. The explanation's paths use real indices. - Reader, formatter, documents.
std/lang/reader.dias: the help for..and....std/lang/fmt.dias: no line break between&and the next form. D015's table and this decision's status; the guide ofdiaspar doc. The compiler's own sources may use the new form only after the seed is regenerated (design/self-hosting.md).
Questions for the author
Answered on 2026-11-18: 1 to 4 and 6 as recommended; 5: & stays, and a vector literal may spread a sequence, #[a & xs z], the construction counterpart of the pattern (several & allowed in a literal, each followed by one expression; the result is a vector); 7: recorded in open-questions.md, for when inference knows a value is a sequence.
- Patterns after the rest, by the rules above? Recommended: yes.
- The rest is a list for a vector too, as today? Recommended: yes; the other answer is "the kind that was matched", which makes
#[x & more]loops over vectors quadratic and#[& init last]on a unique vector free. - After
&, a name or_only in a sequence pattern? Recommended: yes. It removes what only the evaluator accepts (#[a & #[b c]]). - Parameter vectors stay as they are, with the end taken in the rest's pattern,
[a & #[& mid z]]? Recommended: yes. &stays? Recommended: yes. And, apart from this decision: is a spread wanted in vector literals,#[a & xs z], for the 193 lines that build a vector withconcattoday?- A
Rangevalue (D036) and a sequence pattern: no match, as for anyIterable, or a match for a finite range, in constant time? Recommended: no match, and the note "a sequence pattern takes a list or a vector: write (vec r)" in the error. - A warning for lengths no clause handles, when inference knows the value is a sequence? Not part of this proposal; the model is above.