Mojo Lambdas
A lambda is a tiny function without a name, written as a single expression right where you need it. Mojo added lambdas in version 1.0. They look a lot like Python’s, with two differences you’ll notice right away: the arguments need types and parentheses, and the return type has to be written out. Lambdas are perfect for the small bits of behavior you pass to other functions, like “how to compare two items” when sorting.
Your first lambda
Section titled “Your first lambda”Here’s a lambda that adds one to a number, stored in a variable and then called:
def main(): var inc = lambda (x: Int) -> Int: x + 1 print(inc(4))
var add = lambda (a: Int, b: Int) -> Int: a + b print(add(2, 3))
var hello = lambda (name: String) -> String: "Hello, " + name print(hello("Ana"))
var answer = lambda -> Int: 42 print(answer())Output:
55Hello, Ana42Reading lambda (x: Int) -> Int: x + 1 from left to right:
lambdastarts it.(x: Int)is the argument list, with types, just like adef. With no arguments, leave the parentheses out (lambda -> Int: 42).-> Intis the return type.- After the colon comes the body: one expression. Its value is what the lambda returns. There’s no
returnkeyword.
That first lambda does the same job as this function:
def inc(x: Int) -> Int: return x + 1So why bother? Because a lambda can go inline, right inside a function call, without inventing a name for something you use once. You’ll see that in a moment.
Coming from Python: the two big differences
Section titled “Coming from Python: the two big differences”In Python you’d write lambda x: x + 1. Mojo doesn’t accept that, and its error message shows the Mojo way:
def main(): var inc = lambda x: x + 1 print(inc(4))hello.mojo:2:22: error: unparenthesized lambda arguments are not supported; write them in parentheses, with types, e.g. `lambda (x: Int, y: Int) -> Int: x + y` var inc = lambda x: x + 1 ^mojo: error: failed to parse the provided Mojo source moduleThe second difference is easier to miss. If you leave out the return type, Mojo doesn’t figure it out from the body. It assumes the lambda returns nothing (None):
def main(): var inc = lambda (x: Int): x + 1 print(inc(4))hello.mojo:2:34: error: cannot implicitly convert 'Int' value to 'None' in return value var inc = lambda (x: Int): x + 1 ~~^~~mojo: error: failed to parse the provided Mojo source moduleSo “cannot convert … to ‘None’” on a lambda almost always means “add -> Type”. The lambda expressions reference notes that return-type inference isn’t implemented yet, so this may change in a later version.
One expression, but a useful one
Section titled “One expression, but a useful one”The body is a single expression, so there are no if blocks, loops or return statements inside a lambda. A conditional expression (a if condition else b) is fine, since that’s an expression:
def main(): var is_even = lambda (n: Int) -> Bool: n % 2 == 0 var size = lambda (n: Int) -> String: "big" if n > 10 else "small"
print(is_even(4), is_even(7)) print(size(5), size(50))Output:
True Falsesmall bigOnce a lambda needs more than one line of logic, write a normal def instead. That’s not a workaround; it’s the intended split.
Passing a lambda to a function
Section titled “Passing a lambda to a function”This is what lambdas are for. Here’s a function that counts how many values pass a test. The test itself is a function argument:
def count_if[F: def(Int) -> Bool](check: F, values: List[Int]) -> Int: var count = 0 for v in values: if check(v): count += 1 return count
def main(): var scores: List[Int] = [55, 90, 72, 38, 81] print(count_if(lambda (s: Int) -> Bool: s >= 70, scores)) print(count_if(lambda (s: Int) -> Bool: s < 50, scores))Output:
31[F: def(Int) -> Bool] says “F is some function that takes an Int and returns a Bool”, and check: F receives it. That’s the same pattern you saw in Mojo Closures. Each call passes a different lambda, so the same count_if answers two different questions.
The same idea works for building a new list from an old one:
def transform[F: def(Int) -> Int](f: F, values: List[Int]) -> List[Int]: var result = List[Int]() for v in values: result.append(f(v)) return result^
def main(): var nums: List[Int] = [1, 2, 3, 4] print(transform(lambda (x: Int) -> Int: x * 10, nums)) print(transform(lambda (x: Int) -> Int: x * x, nums))Output:
[10, 20, 30, 40][1, 4, 9, 16]Sorting with a lambda
Section titled “Sorting with a lambda”The standard library’s sort function takes an optional comparison function. It should return True when its first argument belongs before the second. A lambda is the natural way to write one:
def main(): var nums: List[Int] = [5, 2, 9, 1] sort(nums) print(nums)
sort(nums, lambda (a: Int, b: Int) -> Bool: a > b) print(nums)
var words: List[String] = ["fig", "banana", "kiwi", "apple"] sort(words, lambda (a: String, b: String) -> Bool: a.byte_length() < b.byte_length()) print(words)Output:
[1, 2, 5, 9][9, 5, 2, 1][fig, kiwi, apple, banana]Without a lambda, sort uses the normal order. a > b sorts biggest first, and comparing byte_length() sorts words from shortest to longest. You’ll do much more with this in Mojo Sorting & Searching. The sort function docs list the options, such as stable=True.
Lambdas that use outer variables
Section titled “Lambdas that use outer variables”A lambda can use variables from around it. Unlike a nested def, it doesn’t need a capture list for this: without one, it captures every outer variable it uses as a read-only reference, the same as {imm}:
def main(): var bonus = 10 var add_bonus = lambda (x: Int) -> Int: x + bonus
print(add_bonus(5)) bonus = 100 print(add_bonus(5))Output:
15105Because it’s a reference, the lambda sees bonus change. A lambda that captures something is a closure, so the capture conventions from the last lesson all work here too. Add a capture list between the arguments and the ->:
def main(): var bonus = 10 var snapshot = lambda (x: Int) {var bonus} -> Int: x + bonus bonus = 100 print(snapshot(5), bonus)
var seen: List[Int] = [] var remember = lambda (x: Int) {mut seen}: seen.append(x) remember(3) remember(7) print(seen)Output:
15 100[3, 7]{var bonus} copies bonus when the lambda is created, so it keeps using 10. {mut seen} lets the lambda change the list. That second lambda has no return type, because append returns nothing.
An empty capture list, {}, means “capture nothing”. Using an outer variable then is an error:
def main(): var z = 10 var f = lambda (x: Int) {} -> Int: x + z print(f(1))hello.mojo:3:44: error: Could not infer capture convention of the captured value z var f = lambda (x: Int) {} -> Int: x + z ^mojo: error: failed to parse the provided Mojo source moduleLambdas that don’t capture can be returned
Section titled “Lambdas that don’t capture can be returned”A lambda that uses nothing from its surroundings is called thin. It’s just code, with no data attached. Thin lambdas can do something closures can’t: you can return one from a function.
def pick(op: String) -> def(Int, Int) thin -> Int: if op == "add": return lambda (a: Int, b: Int) -> Int: a + b return lambda (a: Int, b: Int) -> Int: a * b
def main(): var plus = pick("add") print(plus(3, 4)) print(pick("multiply")(3, 4))Output:
712The return type def(Int, Int) thin -> Int reads “a thin function that takes two Ints and returns an Int”. You’d use this to choose behavior at runtime, like picking an operation from user input. A lambda that captured op couldn’t be returned this way, for the same reason a closure can’t. The Mojo manual’s page on lambdas shows more uses of thin lambdas, including passing them to C code.
Lambda or def?
Section titled “Lambda or def?”| Use a lambda when… | Use a def when… |
|---|---|
| The behavior is one short expression | It needs several lines, a loop or an if block |
| It’s used once, right where you write it | It’s used in several places |
| A name wouldn’t add anything | A good name makes the code easier to read |
When an inline lambda starts making a function call hard to read, give it a name with def (or at least put the lambda in a variable).
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Basic lambda | lambda x: x + 1 |
lambda (x: Int) -> Int: x + 1 |
| No arguments | lambda: 42 |
lambda -> Int: 42 |
| Return type | Never written | Required (otherwise it’s None) |
| Body | One expression | One expression |
| Use outer variables | Automatic | Automatic read-only; {mut x}, {var x} to change that |
| Sort with a key | sorted(words, key=len) |
sort(words, lambda (a: String, b: String) -> Bool: ...) compares two items |
Practice
Section titled “Practice”1. Cubes
Section titled “1. Cubes”Use the transform function from this page with a lambda to turn [1, 2, 3] into their cubes.
Hint: a cube is x * x * x. Don’t forget -> Int on the lambda.
Show solution
def transform[F: def(Int) -> Int](f: F, values: List[Int]) -> List[Int]: var result = List[Int]() for v in values: result.append(f(v)) return result^
def main(): var nums: List[Int] = [1, 2, 3] print(transform(lambda (x: Int) -> Int: x * x * x, nums))Output:
[1, 8, 27]The lambda is written inline, right where transform needs it.
2. Longest word first
Section titled “2. Longest word first”Sort ["kiwi", "fig", "banana", "plum"] so the longest word comes first, using sort and a lambda.
Hint: return True when a is longer than b. Compare with .byte_length().
Show solution
def main(): var words: List[String] = ["kiwi", "fig", "banana", "plum"] sort(words, lambda (a: String, b: String) -> Bool: a.byte_length() > b.byte_length()) print(words[0])Output:
bananaa.byte_length() > b.byte_length() puts longer words first. Only the first word is printed, because kiwi and plum have the same length and their order isn’t guaranteed (the default sort isn’t stable).
3. Above the average
Section titled “3. Above the average”Given var temps: List[Int] = [18, 25, 21, 30, 16] and var average = 22, use the count_if function from this page to count the temperatures above average.
Hint: the lambda can use average directly, since lambdas capture outer variables by default.
Show solution
def count_if[F: def(Int) -> Bool](check: F, values: List[Int]) -> Int: var count = 0 for v in values: if check(v): count += 1 return count
def main(): var temps: List[Int] = [18, 25, 21, 30, 16] var average = 22 print(count_if(lambda (t: Int) -> Bool: t > average, temps))Output:
2The lambda captures average as a read-only reference without a capture list. 25 and 30 are above it.
- A lambda is a nameless one-expression function:
lambda (x: Int) -> Int: x + 1. - Arguments need parentheses and types, and you must write the return type (otherwise it’s
None). - The body is one expression, with no
return; use adeffor anything longer. - Lambdas shine inline, passed to functions like
count_if,transformorsort. - Without a capture list, a lambda reads outer variables by reference (
imm); use{var x},{mut x}or{}to change that. - A thin lambda (no captures) can be returned from a function.
Next up: lists, Mojo’s growable collection, where lambdas and loops get plenty of use.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Lambda expressions (Mojo manual): the official guide, with higher-order functions and thin lambdas.
- Lambda expressions reference: the full syntax, defaults and current restrictions.
- sort (std docs): the sort function and its comparison argument.
- Mojo v1.0.0 release notes: where lambda expressions were introduced.