Lambda functions

From Computer Science Wiki
Jump to navigation Jump to search
A function f takes an input x, and returns a single output f(x). One metaphor describes the function as a "machine" or "black box" that for each input returns a corresponding output.[1]

Introduction[edit]

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.

Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.

Python

def adder(x):
    return lambda y: x + y
add5 = adder(5)
add5(1)
6

As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have[2]


# Define the function

def double(two):

   return lambda a: a * two

# Sets the variable doubler equal to the function double with the parameter "two" equal to 2

doubler = double(2)

# Asks the user which number should be doubled.

NumberToDouble = int(input("What number should I double? "))


# prints doubler with NumberToDouble going in the lambda as "a"

print(doubler(NumberToDouble))


Another Example:

names = ["Bill MacKenty", "Joe Shmoe", "Jan Kowalski", "Max Haltre"]

names.sort(reverse=True, key=lambda names: names.split(" ")[-1].lower())

print(names)


References[edit]