Stories: Functions, Methods, and Lambdas
See also:
spec/functions.md— the rules these chapters explain.
Pulling methods out of the type body
The verb model reads, in the spec, like a top-down unification: one callable, five kinds, each selected by a marker. That is the shape it settled into, but it is not how it was reached. We did not set out to prove that methods, functions, constructors, operators, and lambdas were secretly one construct. Each was designed on its own terms, and we noticed the unity afterward and named it. The honest starting point was much smaller and much more particular: a dislike of where methods live in most languages.
In the mainstream object model a method is written inside the type’s body — a function nested in the class or struct braces, with an implicit receiver. Two features of that design always grated. It groups the behavior with the data, which sounds tidy until you want to add a method to a type you did not declare: the body is closed, so extension becomes a second-class mechanism bolted on the side (extension, free functions that wish they were methods, impl blocks that still cluster by type). And it indents — every method sits a level deeper than a free function for no reason but its enclosure, and in a long body that enclosure is exactly what you lose track of. Scrolling through a hundred lines of indented functions, all sharing one unstated this, you forget which type you are even inside; the receiver is the most important fact about each method and it is the one fact the syntax has pushed off-screen. We could have kept methods in the body and accepted this, the way nearly every OO language does, or grouped them in impl blocks the way Rust does — but an impl block still gathers methods by type and still indents them, so it fixes the extension complaint only halfway and the indentation one not at all.
So we pulled the method out. A method became an ordinary package-scope declaration whose first parameter is the receiver, named this. Nothing encloses it; nothing indents it; and the receiver, instead of being an invisible ambient binding, is written right there at the front of the parameter list where you cannot miss it. Extension stops being a special feature at the same stroke: if a method is just a package-scope declaration with a this first parameter, then any package can write one on any type, and cross-package extension methods need no new machinery — they are the ordinary case, not an escape hatch (see functions.md §6).
That move forced a question it did not answer: if a method is just a function with a differently-named first parameter, what is left of the distinction? Why have methods at all, rather than declaring every operation a free function? The answer we settled on is that the this marker has to earn its existence by granting a capability a plain function cannot have, and that capability is private-field access — the right to read and write the _-prefixed fields of the receiver type (functions.md §2.2). Name your first parameter this and you are writing against the type’s internals; name it anything else and you are a function that sees only the public surface. That access makes an ordinary read-only method a meaningful category and not just a free function wearing a receiver: it has a deeper connection to the type, and the this token declares that connection. The privacy travels with the token, not with the package — a method declared three packages away still reaches _ fields, because it is the this marker that grants the access, not home-package membership. It is the same orthogonality that lets init{ } ride on the name-is-a-type marker for constructors: one small piece of surface form, one capability unlocked, no separate mechanism.
Only once methods lived at package scope did the rest of the collapse become visible, and it became visible without being engineered. A constructor was already a package-scope declaration whose body ends in a value; giving it the marker “the name is a type” made its return type implicit and unlocked init{ }, and it was otherwise an ordinary declaration. An operator was the same declaration with a symbol as its name. A lambda was the same declaration with the name removed. We had not built these to match; they matched because each was, underneath, a package-scope declaration with a statement body that runs to do work. The unified verb model in functions.md §8 is the recognition of that fact, written down after it was already true — one verb, and a handful of markers that each toggle one capability, rather than five parallel features with five sets of rules.
Naming the construct we had found took some care, because the good words were taken or slanted. callable and routine both lean too far toward the function side of the family — they read as synonyms for “function,” which is one member of the set, not the set — and callable is already a term of art elsewhere. procedure carries the opposite bias: in most traditions it implies a call made for its side effects, with no return value, which excludes exactly the constructors and value-returning functions we most needed the umbrella to cover. Reusing function as both the umbrella and one of its members would have been the worst of the three, collapsing the very distinction the word had to help us draw. verb was unclaimed, and its meaning fits: a verb is a word for doing, and the trait shared by every member of the family is precisely that its body executes to do work. The name also draws its own boundary cleanly — a subscript is not a verb, because its body does not run to do work; it projects a place, designating where an element lives rather than computing a value (functions.md §2.9). A construct that only points at storage is not doing anything, so it falls outside the word, and the word itself shows why.
The cost of the marker model is that it loads meaning onto small, quiet pieces of surface form. Renaming a first parameter from this to node does not look like it changes anything, but it silently demotes a method to a function and revokes its access to _ fields; the capability is real but invisible except through the token that grants it, so an edit that reads as cosmetic can change what the body is allowed to touch. And the decision to let privacy ride on the this marker regardless of package is a genuine loosening: _-field privacy is a convention the whole ecosystem is trusted to honor, not a wall the compiler builds around a module. Any package may declare a this method on your type and reach inside it. We judged that acceptable — the _ prefix makes the reach visible at every use, and the alternative of package-sealed privacy would have taken extension methods back out of reach — but it is a real transfer of trust from the compiler to the naming convention, not a free consequence of the design.
Mutation you can see at the call site
Pulling the receiver into the parameter list put it in plain sight at the declaration; the next question was what the receiver looks like at the call. The reasoning about what a method may mutate — only this, only through the receiver, one writable object per call — belongs to the effect model and is recorded in the effects story; it was largely settled before this document had to state any rule. The question left for the function surface was narrower: whether a caller can see, at the call site, that a call is going to mutate the object it is called on.
Most languages answer no, and not by oversight. In player.reload() there is nothing in the call to tell you whether reload changes the player or merely reports on it; the mutability lives in the method’s declaration, or in the reference-ness of a parameter, and the call site is silent about it. We could have followed that — one call syntax, mut visible only where the method is declared — and it would have been less to learn. We rejected it because it hides exactly the fact we most wanted legible. If the language has already gone to the trouble of guaranteeing that a call mutates at most one object, the receiver, then a reader should be able to collect that guarantee by eye, without opening a single signature. So a read-only call is written with : and a mutating call with ! (functions.md §2.5), and the two are not interchangeable: calling a mut method with : is illegal, and calling a read-only one with ! is illegal. node:scaledId(...) cannot touch the node; node!setScale(...) can. You read the mutation off the punctuation.
The other road we did not take was the C++ one — make mutation a property of a reference parameter, pass the receiver by mutable reference, and let that carry the write permission. That buries the signal even deeper than the declaration-only approach: now mutability is a property of a type spelling buried in the parameter list, and the call site shows nothing at all. It also reintroduces the mutable-reference machinery the memory model was built to avoid. Putting the whole signal in a single call-site character keeps mutation visible without any of that apparatus.
The cost is a deliberate redundancy. The mutating-ness of a call is now stated twice — once by mut on the declaration, once by ! at every call — and the compiler checks that the two agree. That is duplication, and duplication is usually a smell; here it is the point, because the reader gets the second statement for free at the call site, and the check turns a possible mismatch into a compile error rather than a silent wrong assumption. The inherent price is that a method’s mutability is now part of how it is called, not just how it is written: the read-only-versus-mutating distinction is welded to the call syntax, so the two capabilities can never share a spelling. Two of the surface’s scarce sigils are spent buying that, permanently.
Overloading on shapes, and only shapes
With calls marked and receivers in the parameter list, a call is fully described by the shape of its arguments — and that is exactly what we decided overload resolution is allowed to look at, and nothing else. Two declarations in the same package are the same overload if they have the same ordered parameter types (functions.md §4.1). Names do not distinguish them, because a call supplies arguments positionally and never sees a parameter’s name. Return type does not distinguish them, because a bare call in a discarding position constrains nothing about what comes back, so return-type overloading would leave calls that no context could resolve. And mut does not distinguish them, because — as the effect model has it — the call contract of a read-only and a mutating method with the same parameters is structurally identical; mut changes the body’s permissions, not the call’s shape, so it cannot distinguish two calls.
One case looks like it should be allowed and is specifically forbidden: two overloads that differ only by & on the same parameter position (functions.md §4.3). The reason is that a &T parameter and a plain T parameter are called with identical syntax — the caller writes the same argument either way, and whether a new guest is created is decided by the parameter mode, not by anything at the call (functions.md §2.8). Two candidates that a call cannot distinguish are not an overload set the compiler can resolve; rather than invent a tiebreak nobody could see, we make the declaration illegal and ask the author to rename one or pick a single signature.
That leaves the order in which candidates are tried, and here the pressure was to keep implicit conversions from ever surprising you. Resolution runs in three phases: an exact direct match first, then a generic match that infers the callee’s type and number parameters from the argument types, then an implicit match that is allowed to insert implicit constructors at coercion sites (functions.md §5). The ordering is the whole content of the rule. If an exact match exists, it wins outright, so adding an implicit conversion elsewhere in the program can never quietly steal a call that already had a precise home. And the generic phase runs before implicit conversions and without them, so type inference is never asked to discover an unknown destination type through a coercion — inference reads types that are actually present on the arguments, and implicit construction is a last resort that only runs once both exact and generic matching have come up empty. Implicit conversions stay a convenience at the edges rather than a force that reshapes which function you called.
The cost here is honestly small, which is worth saying plainly rather than dressing up. Restricting overload identity to parameter shape does close a couple of doors other languages leave open: you cannot write two methods that differ only in return type and let context select one, and you cannot pair a read-only and a mutating overload under one signature and one name — the mutating one is reached by ! on a declaration whose parameters differ, or it is a different declaration. Those are real expressive narrowings, but they are narrow, and each one buys a call site that resolves the same way no matter what conversions or context surround it.
Names that are not values
Everything so far treats a callable as a declaration you invoke, and overloading makes anything else a problem. An overloaded name is not one callable; it is a set of candidates that only collapses to a single member when arguments arrive at a call site and select one. In value position there are no arguments, so there is nothing to collapse the set — and if you then tried to pass that unresolved set as an argument to a callable that was itself overloaded, both overload sets would have to resolve at once, each waiting on the other for the information it needs. So the last decision is that in this language invoking is the only operation on a callable. A method, a function, an operator — its name may appear in call position and nowhere else. You cannot write the name of a function as a value, store it, or pass it; + can be called but not handed around (functions.md §7.1). This looks like a restriction until you see what it removes. Making callables call-only deletes that entire class of ambiguity by construction, which is the same reason operators are safe to overload freely (operators.md §5.3).
But callbacks are real, and a language needs a means of passing behavior as data. The lambda is that means, and it works precisely because it is built to be the opposite of an overloaded name: a single value with one exact type. A lambda literal writes its own complete type — parameter types, return type, abort type, and mut — and infers nothing from its surroundings (functions.md §7.2). Because it carries its whole type, it is already collapsed to one member; there is no set to resolve, so it can be passed straight into an overloaded receiver by exact shape match, no circularity anywhere. To name a function value you declare a lambda-variable — a symbol bound to a lambda literal — and because a symbol has one type and can never accumulate an overload set, the name is always unambiguous in value position where a bare callable name would not be (functions.md §7.3). The self-typing is not ceremony; it is the property that lets a function value coexist with overloading at all.
Two consequences of the lambda’s design are worth naming as costs, because they are the parts a later reader will want to have been warned about. Lambdas do not capture: every value a lambda uses must be passed as a parameter or reached through explicit storage, never closed over from the surrounding scope (functions.md §7.4). That keeps data flow explicit and keeps effect and concurrency analysis tractable — a function value cannot smuggle in hidden mutable state for a parallel task to trip over (concurrency.md §5.2) — but it is a real ergonomic price: closures are a convenience most languages grant, and here every dependency rides in the open. It also rules out bound method references: because nothing is captured, there is no syntax that quietly tucks a receiver inside a function value, so code that needs a receiver later must keep it in ordinary storage and pass it back explicitly at the call. And a function value that is itself generic — polymorphic over its own type or number parameters — is left unspecified in this version, not because overloading cannot cope with it (a generic function type is still one unique parameter shape) but because its runtime representation, monomorphization versus dictionary passing, is a memory-model question we have not answered; that gap is owned by the generics story’s deferred account alongside the other places the model promises more than it yet delivers.
Every return carries a value
Making Unit a real value raised a choice between convenient procedure syntax and a uniform return checker. We first leaned toward convenience: a Unit verb could fall through or use bare return, with the compiler supplying Unit() because no other result was possible. A user-defined empty type would still need return MyUnit() because its constructor could execute arbitrary code. That separation was locally defensible and globally the wrong shape.
The problem was not whether synthesizing Unit() was safe; it was where the knowledge had to live. Unit is declared by the bundled core implementation like the other fundamental types. Giving it fallthrough would require a special case in return-path analysis and AST lowering solely for that nominal declaration. Bool does not set a precedent: an if node already checks a condition, so choosing Bool as the expected type only fills an existing slot. A return node with no expression has no such slot to check; the compiler would have to create the expression.
We therefore took the strict rule we had initially rejected. Every returning path carries an explicit value, so a Unit verb ends in return Unit() and an expression body writes Unit noOperation() => Unit(). The cost is repetition where the signature already proves there is only one possible value. What it buys is more fundamental: Unit stays ordinary all the way through the compiler, and every return AST has the same shape regardless of the type travelling through it.
Renaming the receiver to the subject
The rules in this document had used “receiver” from the first draft, and we never looked at the word once. It arrived free with the object model, the way it arrives free in Go, Swift, Ruby, and Java’s documentation, and a word that every neighbouring language already uses does not attract the scrutiny a coined one does. It survived the whole of the passing-mode work by being invisible.
What eventually broke it was a rule that had to talk about this specifically. Taking the bare symbol away as a guest source forced us to define a bare this T on a reference type, and the sentence we reached for — the receiver is never a swallow position — turned out not to parse. A reader asked which receiver was meant, and the honest answer was that the word had been covering three constructs at once: the object a method is called on, the this parameter whose surface form determines how that object arrives, and the expression standing left of : or ! at the call site. The rule was about the second; the reason behind it was about the third; “stores or returns the receiver” was about the first. All three were true, and the sentence let a reader pick the wrong construct. So we split them — subject, subject parameter, subject expression (glossary.md §3.38) — and thought that was the end of it.
It was not, because the next question actually landed: “what does a receiver receive?” In Smalltalk the answer is a message. A call was a message, sent to an object, and the object that took delivery was its receiver — the metaphor was exact, and it was load-bearing, because the message could be forwarded, reified, or not understood. Every language that copied the object-dot-method shape kept the noun and dropped the machinery underneath it. Zane has no messages. A method here is a package-scope verb whose first parameter is this, and player!setScale(...) desugars to a plain call with the object in first position (functions.md §2.1). Nothing is sent, so nothing is received.
That is a worse failure than it first sounds, and our own naming guide makes it legible. The test we apply to a candidate term is whether a fresh reader’s existing sense of the word points toward the concept or away from it — whether it feeds or fights. receiver did neither. It is a dead metaphor: a label with no analogy left underneath, teaching nothing on contact and quietly inviting the reader to look for a delivery that does not exist. We had rejected origin form for being flat and descriptive; receiver is flatter, and it describes a false relation.
The replacement was sitting in the register we had already committed to. This document calls callables verbs because a verb is the word that acts — and grammar, having lent us that, has the rest of the sentence to lend as well. A call reads subject–verb–object: in player!setScale(scale) the subject is player, the verb is setScale, the object is what it acts on. The subject is the party the verb acts from, and this is precisely that party, and a reader who has met the word in a sentence already knows that much before reading a definition. It is short, ordinary, unremarkable in dense prose, and it makes the whole parameter list nameable in one register instead of one word borrowed from grammar and one from a message-passing model we do not implement.
We weighed keeping receiver anyway, on the strength of every other language using it — a real argument, since a term’s job is to be understood, and familiar-but-hollow may beat apt-but-strange. We decided the familiarity was worth less than it looks: a reader who knows receiver from Go knows it as a position, not as a metaphor, so nothing is actually lost when the position keeps its meaning under a better name. target was the other candidate and was rejected quickly — “call target” already means the function being called, so it would have collided with the one part of a call it must never be confused with.
subject is not free of prior claims. It is the observer pattern’s Subject, and in security it is the principal a policy is written about. That is a weaker collision than the collision that sank matrix — neither of those meanings is likely to be in a reader’s mind while reading a method signature — but it is not nothing, and it is the honest cost of the choice.
The larger cost is one this file is currently demonstrating. The spec is rewritten to the present, so every rule now uses subject; the stories are not, so every chapter above this one still uses receiver, and always will. A reader working through the design history meets both words for one concept and must carry the mapping themselves. We accepted that deliberately rather than quietly reaching back to rewrite the earlier chapters: an accurate record of the reasoning we actually had, in the words we actually had it in, is worth more than a uniform vocabulary. This chapter is the mapping.
Lambda mut permission in overload matching
Names that are not values had a lambda passed into an overloaded callee “by exact shape match”. That was nearly true, and the gap between nearly and exactly turned up when the compiler first had to run function values. A lambda that does not declare mut may be held by a mut function type (functions.md §7.2): mut on a function type is a permission, and a lambda that never writes its subject is safe wherever writing is allowed. The compiler honored that for a declaration and refused it for an argument. So callback Unit[this Node] mut = Unit(this Node) { ... } followed by register(callback) compiled, and register(Unit(this Node) { ... }) did not, though it is the same value going to the same place.
The strict reading had a defence, and it was the word “exact”. If an argument could match with the relaxation, then two overloads that differed only in whether their callback parameter was mut would both accept a lambda that does not declare mut, and the call would be ambiguous. The compiler accepted exactly such a pair, and that acceptance made the strictness look necessary. It was not. The rule that closed the question had been in the shapes chapter all along: mut does not distinguish overloads, because it changes a body’s permissions and not the call’s shape. That is as true of the mut inside a function-type parameter as of the mut on a declaration, and it is the same reasoning that made two overloads differing only by & illegal: the caller writes the same argument for both, so nothing at the call site could select one.
So we made it explicit (functions.md §4.1). Two overloads may not differ only by the mut of a function-type parameter, and with that no call can match two of them, so an argument gets the same relaxation a declaration always had. A lambda still goes to an overloaded callee by its shape. The shape is now exact up to one permission the lambda does not need to use.
The cost is the cost the shapes chapter already paid for methods: a callee cannot offer one overload for callbacks that write their subject and another for those that do not. If both are wanted, they are two names.
this keeps only the subject call
When field privacy moved to the package, the this marker lost the capability that the first chapter gave as its reason to exist. That chapter’s answer to “why have methods at all” was private-field access. With access decided by package, a function in the type’s package reaches _ fields as well as a method does, and a method in another package reaches them no better than a function there.
We asked whether methods had to go with it, and they did not, because private access had never been the only capability this granted. A method is called on its subject, node:scaledId(factor) or node!setScale(scale), so the call names the object first and states with : or ! whether the object changes, which is what the call-site chapter built. And the subject is a borrow of the caller’s storage, the one parameter a mut method may write through. Those were capabilities all along; the first chapter counted private access as the capability that justified the token and the rest as consequences. So this now grants the subject call (functions.md §2.2), and the marker table of functions.md §8 lists that as what a method unlocks.
The first chapter’s cost paragraph goes with the capability. Renaming this to node now changes how a verb is called, not what its body may touch, and the trust that rule had moved onto the naming convention is back with the compiler. The cost runs the other way now. A method no longer declares a deeper connection to its type: this does not tell a reader whether the body works against the type’s internals, and only the _ at each use and the package the verb sits in do. The parallel with init{ } is looser too. The name-is-a-type marker still unlocks a capability inside the body, while this now unlocks a capability at the call site.
Computations are functions, and math functions with them
When core gained its math functions (the math story), we had to decide how a program would call them, as x:sqrt() or as sqrt(x). Neither form was wrong under the rules we had. A method is only a verb whose first parameter is this, and a function is the same verb without it, so the question was the meaning the choice should carry.
Our first recommendation was methods, the way Rust writes them. Their strongest argument in Zane is lookup: an unqualified method call searches the home package of its subject’s type first (functions.md §6.1), so x:sqrt() would find core’s sqrt in any file holding a Float, however that file had imported core, and no other package’s sqrt could take its place. Methods also chain left to right, (dx * dx + dy * dy):sqrt(), and an editor completing x: would list them. Most other languages go the other way. C, Go, Java, Python and Julia write sqrt(x), Swift mixes the two with x.squareRoot() beside a free sin(x), and Rust’s methods are criticised for the one place they read badly, the functions with two equal inputs. a.min(b) singles out an operand that is not special, and y.atan2(x) hides which argument is which. So our second proposal was Swift’s split: one-input functions as methods, two-input ones as functions.
We turned both down for a rule about meaning rather than shape. A method reads or acts on its subject’s own state: node:scale() retrieves what a Node holds, and node!setScale(s) changes it. sqrt retrieves nothing stored in a Float. It computes a new value from an input, as atan2 computes one from two and fma from three, and writing one of those inputs on the left of a : claims a relationship it does not have. So a computation from inputs is a function, and an operation on a subject is a method (functions.md §3.6). Every math function in core is called by name (math.md §3.1), with all its inputs in the same position, and the asymmetry of a:min(b) cannot arise.
The rule reached past math as soon as it was written down. functions.md §3.1 had shown a function with Float getScale(node Node), which returned node.scale and was exactly a read of a subject written as a function. Its example became distance(from, to), a computation from two inputs. The rule is stated as core’s practice and a recommendation for packages, not as a check the compiler makes, because the line between reading state and computing from it is a judgement a declaration’s signature cannot show.
The lookup argument for methods turned out smaller than it looked. Most files already write import core$ to get Int, which brings the math functions into scope with it, and a package’s own sqrt(Vec2) imported beside core’s joins one overload set rather than colliding (packages.md §3.8). The cost is what methods would have given. A file that imports only core$Int writes core$sqrt(x) or adds the name to its import, a long expression is wrapped in sqrt( ) rather than finished with :sqrt(), and completing x: lists nothing about math.