Proposal: Fat-Arrow (=>) Closures
1. Syntax & Semantics
Mojo adopts => as a structural anchor to support anonymous functions without the lambda keyword or C-style curly braces.
A. Single-Line Form (Implicit Return)
Single-line arrows evaluate directly as expressions and implicitly return their result.
# Single parameter (parentheses optional)
var double = x => x * 2
# Typed multi-parameter
var multiply = (a: Int, b: Int) -> Int => a * b
B. Multi-Line Form (Explicit return Required)
Triggered when => is followed immediately by a newline (\n). Multi-line closure blocks require an explicit return statement.
var results = numbers.map(x =>
var square = x * x
var cube = square * x
return square + cube # Explicit return required
)
C. Positional Arguments & Baseline Commas
Argument commas following a multi-line closure must sit at or outside the parameter baseline (on a new line) to dedent the block properly:
async_dispatch(
on_success = data =>
var clean = sanitize(data)
return process(clean)
, # Baseline comma exits block context and separates arguments
on_error = err =>
return log(err)
)
2. Compiler Architecture
-
Cover Grammar: The parser parses candidate parameter lists
(...)as standard parenthesized expressions and promotes them to closure heads only when encountering=>. -
Dual Lexer Stacks: Line-break suppression inside parentheses is managed using two separate lexer stacks:
-
A Parenthetical Nesting Stack tracking
(),[],{}depth. -
An Indentation Baseline Stack tracking column positions for active
=> \nblocks to triggerINDENTandDEDENTtokens inside argument lists.
-
3. Design Trade-Offs
-
Pros: 100% Pythonic aesthetic, eliminates
lambda, enables multi-line inline logic without brace syntax. -
Cons: Floating baseline commas
,are required when passing multi-line closures as non-final positional arguments. APIs will naturally favor trailing closures or keyword parameters.