๐งโโ๏ธ The Magic Kitchen: A Tale of Functional Programming in Python
Imagine you have a magical kitchen where tiny helpers do special jobs. Thatโs functional programming!
๐ช Welcome to the Magic Kitchen!
Think of functional programming like having a team of tiny kitchen helpers. Each helper does ONE special job:
- One helper squeezes lemons (thatโs a function!)
- Another helper picks only red apples (thatโs filtering!)
- Another helper counts all the cookies (thatโs reducing!)
Letโs meet our magical helpers!
๐ Lambda Functions: The Quick Little Helpers
Whatโs a Lambda?
A lambda is like a tiny helper who does ONE quick job. You donโt even need to give them a name!
Normal helper (regular function):
def double(x):
return x * 2
Quick helper (lambda):
double = lambda x: x * 2
Both do the same thing! But lambda is shorter.
๐ Real Example: Pizza Slices
# Lambda to calculate pizza slices
slices = lambda pizzas: pizzas * 8
print(slices(2)) # 16 slices!
print(slices(3)) # 24 slices!
๐ก When to Use Lambda?
Use lambda for quick, simple jobs:
# Add two numbers
add = lambda a, b: a + b
print(add(5, 3)) # 8
# Check if number is even
is_even = lambda n: n % 2 == 0
print(is_even(4)) # True
graph TD A["Regular Function"] --> B["Has a name"] A --> C["Can be many lines"] D["Lambda Function"] --> E["Can be nameless"] D --> F["Only ONE line"]
๐บ๏ธ Map Function: The Transformation Helper
Whatโs Map?
Map is like a helper who takes a basket of items and does the SAME thing to EVERY item.
Imagine:
- You have 5 apples ๐๐๐๐๐
- You want to peel ALL of them
- Map peels each one!
๐จ Painting Numbers
numbers = [1, 2, 3, 4, 5]
# Double every number!
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# [2, 4, 6, 8, 10]
What happened?
1 โ 2(doubled)2 โ 4(doubled)3 โ 6(doubled)- And so on!
๐ก๏ธ Temperature Converter
celsius = [0, 20, 30, 100]
# Convert all to Fahrenheit
fahrenheit = list(map(
lambda c: (c * 9/5) + 32,
celsius
))
print(fahrenheit)
# [32.0, 68.0, 86.0, 212.0]
graph TD A["Input List"] --> B["Map"] B --> C["Apply Function"] C --> D["To Each Item"] D --> E["Output List"]
๐ Filter Function: The Picky Helper
Whatโs Filter?
Filter is like a helper who picks only the items you want.
Imagine:
- You have a basket of fruits ๐๐๐๐๐
- You only want RED apples
- Filter picks just those!
๐ฏ Finding Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Keep only even numbers
evens = list(filter(
lambda x: x % 2 == 0,
numbers
))
print(evens)
# [2, 4, 6, 8]
What happened?
1โ Odd, thrown away โ2โ Even, kept! โ3โ Odd, thrown away โ- And so on!
๐ถ Finding Kids
ages = [5, 15, 25, 8, 35, 12]
# Find all kids (under 13)
kids = list(filter(
lambda age: age < 13,
ages
))
print(kids)
# [5, 8, 12]
graph TD A["All Items"] --> B["Filter"] B --> C{Passes Test?} C -->|Yes| D["Keep It!"] C -->|No| E["Throw Away"]
๐งฎ Reduce Function: The Counting Helper
Whatโs Reduce?
Reduce is like a helper who takes ALL items and combines them into ONE.
Imagine:
- You have coins: 5ยข + 10ยข + 25ยข
- Reduce adds them all up
- You get 40ยข!
โ ๏ธ Special Import Needed!
from functools import reduce
๐ช Counting All Cookies
from functools import reduce
cookie_jars = [5, 10, 3, 7]
# Add all cookies together
total = reduce(
lambda a, b: a + b,
cookie_jars
)
print(total) # 25 cookies!
Step by step:
- Start:
5 + 10 = 15 - Then:
15 + 3 = 18 - Finally:
18 + 7 = 25
๐ฒ Finding the Biggest Number
from functools import reduce
scores = [85, 92, 78, 95, 88]
# Find highest score
highest = reduce(
lambda a, b: a if a > b else b,
scores
)
print(highest) # 95
graph TD A["Item 1"] --> B["Combine"] C["Item 2"] --> B B --> D["Result"] E["Item 3"] --> F["Combine"] D --> F F --> G["Final Result!"]
๐ญ Higher-Order Functions: The Boss Helpers
What Are They?
Higher-order functions are like boss helpers who can:
- Take other helpers as input (receive functions)
- Create new helpers (return functions)
Guess what? map, filter, and reduce are ALL higher-order functions!
๐ญ Creating a Multiplier Factory
def make_multiplier(n):
return lambda x: x * n
# Create helpers
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
What happened?
make_multiplier(2)created a โdouble helperโmake_multiplier(3)created a โtriple helperโ- Each helper remembers their job!
๐จ Decorator Example
def shout(func):
def wrapper(text):
return func(text).upper() + "!"
return wrapper
@shout
def greet(name):
return f"hello {name}"
print(greet("world"))
# HELLO WORLD!
๐ Passing Functions Around
def apply_twice(func, value):
return func(func(value))
# Double function
double = lambda x: x * 2
result = apply_twice(double, 3)
# First: 3 * 2 = 6
# Second: 6 * 2 = 12
print(result) # 12
graph TD A["Higher-Order Function"] --> B["Takes Functions"] A --> C["Returns Functions"] B --> D["map, filter, reduce"] C --> E["Decorators, Factories"]
๐ Putting It All Together!
Letโs use everything we learned!
๐ Shopping Cart Example
from functools import reduce
cart = [
{"item": "apple", "price": 1.50},
{"item": "banana", "price": 0.75},
{"item": "candy", "price": 2.00},
{"item": "milk", "price": 3.50}
]
# Get all prices (map)
prices = list(map(
lambda x: x["price"],
cart
))
# [1.50, 0.75, 2.00, 3.50]
# Keep only items under $2 (filter)
cheap = list(filter(
lambda x: x["price"] < 2,
cart
))
# apple and banana
# Calculate total (reduce)
total = reduce(
lambda a, b: a + b,
prices
)
# 7.75
๐ฏ Quick Reference
| Function | What It Does | Example |
|---|---|---|
lambda |
Quick helper | lambda x: x * 2 |
map |
Transform all | map(func, list) |
filter |
Pick matching | filter(test, list) |
reduce |
Combine all | reduce(func, list) |
| Higher-Order | Boss functions | Takes/returns funcs |
๐ Remember!
- Lambda = Quick, one-line helper
- Map = Do something to ALL items
- Filter = Pick only what you want
- Reduce = Combine everything into ONE
- Higher-Order = Functions that use other functions
Youโre now a functional programming wizard! ๐งโโ๏ธโจ
