Functional Programming

Back

Loading concept...

๐Ÿง™โ€โ™‚๏ธ 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:

  1. Take other helpers as input (receive functions)
  2. 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! ๐Ÿง™โ€โ™‚๏ธโœจ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.