Skip to the content
Diaspar

Decision D022 · accepted

Operators are protocol methods; strings concatenate with + and interpolate

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-15)

Operators are protocol methods

+ and the other operators are ordinary functions that dispatch through protocols (D010), so user types can implement them, as with Rust's Add, Python's __add__, Swift, and Kotlin. When inference knows both arguments are numbers (D007), the compiler emits the arithmetic directly, with no dispatch.

Operator Protocol Built-in implementations
+ Add numbers; strings (concatenation)
- Sub numbers
* Mul numbers
/ Div numbers (IEEE, D013)
unary - Neg numbers
< > <= >=, compare Ord numbers, strings (byte-wise), dates

= cannot be overridden. Equality is structural for every value (D013), and hashing, map keys, and sets depend on it; a type that redefined = without its hash would break maps, a recurring bug in Python and Java. A type defines ordering through Ord.

(extend-type Vec2 Add
  (add [a b] (Vec2 :x (+ a.x b.x) :y (+ a.y b.y))))

(+ position velocity)

Mixed types: a date plus a duration

Dispatch is on the first argument, so (+ date duration) selects Date's implementation, and its clauses (D015) decide what the second argument may be. The reverse order is not implied: not every addition is commutative (string concatenation is not), so (+ duration date) works only if Duration implements it too. Several arguments fold from the left.

(extend-type Date Add
  (add ([d (Duration :seconds)] (Date :epoch (+ d.epoch seconds)))))

(extend-type Date Sub
  (sub ([a (Date :epoch e)]          (Duration :seconds (- a.epoch e)))
       ([d (Duration :seconds s)]    (Date :epoch (- d.epoch s)))))

(+ today (days 3))              ; a date
(- deadline today)              ; a duration
(+ today (days 1) (hours 2))    ; folds from the left
(+ (days 3) today)              ; error: Duration does not implement Add for Date

Python (datetime + timedelta) and Rust (Instant + Duration) work the same way. Guideline: an operator is implemented only where the domain itself calls the operation addition, subtraction, or ordering; anything else is a named function (add-member, not +), avoiding C++'s <<-for-output kind of overloading.

Operands of different types (accepted, 2026-11-16)

An operator first looks for an implementation in the type of its first argument; if that type has none for the second argument's type, it looks in the type of the second argument, which receives the arguments in their original order. So the author of BigInt writes once how it combines with an integer, and both (+ big 1) and (* 2 big) work, as do the comparisons. This is Python's reflected methods (__radd__) without a second method name. Numbers with numbers keep their fast path. If neither type has an implementation, the error names both: "+ does not mix numbers and BigInt values".

Rejected: implementations only on the first argument's type ((* 2 x) fails for every user type); Rust's way, where the type's author implements the operator for the built-in type too (not possible for protocols dispatched on one argument); Julia's dispatch on both arguments with promotion rules (a larger mechanism than the problem needs).

+ concatenates strings

(+ "Hello, " name)       ; "Hello, Ann"
(+ "count: " 5)          ; error: + does not mix strings and numbers
;;   = help: convert first: (+ "count: " (str 5)), or use an interpolated string

There is no conversion between kinds (D013); JavaScript's trouble with + is "1" + 1, not concatenation. A string held by one reference is appended in place (D004), so concatenation in a loop is not quadratic.

Interpolated strings, as Python's f-strings

f"Hello, {name}!"
f"You have {(count items)} items"     ; any Diaspar expression
f"Total: {price:.2f} {currency}"      ; Python's format mini-language
f"|{name:<10}|{score:>6}|"            ; widths count display columns (D013)
f"{user=}"                            ; debugging: user=(User :name "Ann" …)
f"{{literal braces}}"
  • Only prefixed strings interpolate. A plain string stays data: in a Lisp, strings live in quote, macros, and templates (JSON, regular expressions such as a{3}), where interpolating every { would force escapes everywhere.
  • The reader expands an interpolated string at compile time into str with formatting; there is no run-time parsing, and an error inside {…} points at its place in the string (D014).
  • The format mini-language is Python's (.2f, <10, >6, ,, %, =); widths count graphemes by their terminal columns, as Ferron's D40 and D69.
  • Computed widths and precisions (accepted, 2026-11-17), as Python's nested fields: f"{name:<{width}}", f"{x:>{w}.{p}f}". The inner {…} is an ordinary expression, evaluated before the value is formatted; it must give a non-negative integer, else a BadArgument names the field.
  • The types g and G (accepted, 2026-11-17), with Python's meaning: a precision of significant digits (6 by default), fixed or exponent notation chosen by the exponent, trailing zeros removed unless # is given; G writes E. f"{0.000012345:.3g}" is "1.23e-05", f"{1234.5:.3g}" is "1.23e+03", f"{12.0:.3g}" is "12", f"{12.0:#.3g}" is "12.0". Tests compare the results with CPython's over generated values.

The prefix is f. f"…", as in Python and Scala, is the most familiar to people and coding agents. Alternatives: C#'s $"…"; #"…", matching Diaspar's # prefixes for data literals but clashing with Clojure's regular expression literal; JavaScript's backticks clash with quasiquote; interpolating every string, as Kotlin, Swift, Ruby, and Ferron do, is rejected above.

Raw strings, joined lines and string.dedent (accepted, 2026-11-18; implemented after the Rust interpreter is deleted)

Three kinds of string, as Rust has two plus the f-strings above. Each may span lines; nothing else is needed for long or multi-line text.

"hello\n"                        ; ordinary: escapes \n \t \" \\ \u{…}

"line one
line two"                        ; may span lines; the line break is in the value

"a long line \
 goes on here"                   ; \ at the end of a line: the break and the next line's indentation are dropped

r"C:\Users\ann"                  ; raw: no escapes
r#"she said "hi""#               ; raw, with " inside

f"Hello, {name}!"                ; interpolation, as above

(string.dedent "
  Usage: diaspar build [FILE]
    -o  where to write the binary
  ")                             ; "Usage: diaspar build [FILE]\n  -o  where to write the binary"
  • r"…" and r#"…"#, as Rust's raw strings: nothing inside is an escape; with #, " may stand inside and the string ends at "#. One # is the only form: a text that holds "# is written as an ordinary string.
  • \ at the end of a line inside an ordinary string or an f-string drops the line break and the leading white space of the next line, as in Rust. It is an escape, so raw strings do not have it.
  • string.dedent removes the indentation common to the lines, the line break right after the opening quote, and a last line of only white space. It is a macro over a string literal (ordinary, raw or f-string), so the work is done when the program is built, as Rust's indoc!; Python's textwrap.dedent and Kotlin's trimIndent do the same at run time. On a string that is not a literal it is an ordinary function.
  • Printing is unchanged: a string prints as an ordinary string with escapes.

Rejected: blocks in triple quotes (Swift, C#, Java, Elixir, Python): a fourth and fifth kind of string, with rules about the closing quotes' column and about quotes inside, for what a macro does; raw strings with any number of # (one is enough in practice); rf (raw and interpolated at once is rare; an f-string can escape its backslashes); Go's backquote (quasiquote here); Swift's #"…"# without a prefix (# opens Diaspar's data literals).