What Are The Lambda Functions In Mojo?

If you worked with Python or JavaScript, you might know about anonymous functions. In Mojo, lambda functions serve the same purpose.

A lambda function in Mojo is a small, anonymous function that can be defined in a single line. Anonymous means it does not require a function name, and it is useful for short and simple tasks.

For example:

1) This is a Simple Normal Function:

fn square(num: Int) -> Int:
return num * num

print(square(5)) # Output: 25

You can see, this is a named function (square) that takes a number and returns its square, and you can call it multiple times anywhere in your code.

2) Lambda Function example:

double = lambda x: x * 2
print(double(7)) # Output: 14

Here, lambda x: x * 2 creates a function without using fn keyword. We store it in the variable double so it behaves like a normal function. This is a shorter method, but also usable.

3) Anonymous Function Example (Lambda Used Directly):

print((lambda a, b: a + b)(3, 4))  

# Output: 7

Here, the lambda has no name, and it’s created and called immediately. This is an anonymous function because it is not stored in a variable defined with a name.

In simple terms, a Lambda function is useful in filtering, mapping, sorting, and quick calculations.

Syntax of Lambda Functions in Mojo

lambda arguments: expression
  • arguments → Parameters passed to the function
  • expression → The single expression whose result is returned

Simple Example:

square = lambda x: x * x

print(square(5)) # Output: 25

Why Use Lambda Functions in Mojo?

Why not use only normal functions?

The lambda function used when defining a full function is unnecessary, like one-time use cases such as passing a function to map() or filter().

Real-Life Example: Grocery Price Calculator

We want to calculate the final price for grocery items after applying a discount, but only for items costing more than ₹100.

# List of grocery items (name, price)
groceries = [("Apples", 90), ("Rice", 120), ("Milk", 60), ("Olive Oil", 250)]

# Lambda to apply discount
apply_discount = lambda price: price * 0.9 if price > 100 else price

for item, price in groceries:
final_price = apply_discount(price)
print(f"Item: {item}, Final Price: ₹{final_price}")

Output:

Item: Apples, Final Price: ₹90
Item: Rice, Final Price: ₹108.0
Item: Milk, Final Price: ₹60
Item: Olive Oil, Final Price: ₹225.0

In this code, the lambda function applies a 10% discount only to items above ₹100.

How To Use Lambda with map() and filter()?

We can use a lambda function together with built-in functions like map() and filter() to process data quickly without writing long functions.

Example 1 – Filtering Even Numbers

numbers = [10, 15, 20, 25, 30]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]

In this example:

  • We have a list of numbers.
  • the filter() method checks each number and keeps only the ones where the condition is True.
  • lambda x: x % 2 == 0 → This is a condition. If the number is divisible by 2 → it’s even → keep it.
  • list( . . . ) converts the filtered result back into a list.

Example 2 – Doubling Numbers

numbers = [2, 4, 6]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [4, 8, 12]

In this code, map() applies a function to each item in the list, and the function multiplies each number by 2, then list (. . . ) converts the result into a list again.

How To Use Lambda Inside Sorting?

We can use a lambda function to sort based on a custom condition. For example:

students = [("Amit", 85), ("Priya", 92), ("Rahul", 78)]

# Sort by marks (descending order)
students.sort(key=lambda student: student[1], reverse=True)
print(students)

Output:

[('Priya', 92), ('Amit', 85), ('Rahul', 78)]

Exercise For Practice

Problem Statement:
Create a Mojo program with the following terms:

  1. You have a list of exam scores.
  2. Use filter() with a lambda to select only scores above 50.
  3. Use map() with a lambda to add 5 bonus marks to each selected score.
  4. Print the updated scores.

Expected Output Example:

Updated Scores: [72, 89, 95]

Also Learn this Topics:

Leave a Comment