Functors, Applicatives, and Monads with Real-Life Examples
Functors: The Package Delivery Service
Real-Life Example: Think of a package delivery service.
Explanation:
The package is your value in a context (the "box")
The delivery service has protocols for handling packages
When you want to modify something inside a package without opening it:
You give the delivery service special instructions (a function)
They apply these instructions to the package's contents while maintaining all delivery protocols
For example:
A package containing a shirt (Just shirt)
You want the shirt ironed (+iron)
The delivery service applies
fmap iron packageYou receive a package with an ironed shirt (Just ironedShirt)
If the package is empty (Nothing), no action is taken - you still get an empty package back.
This reflects how fmap applies a function to a value in a context while preserving the context.
Applicatives: The Customizable Gift Service
Real-Life Example: A customizable gift service.
Explanation:
You have gift items in boxes (values in contexts)
You also have customization instructions in envelopes (functions in contexts)
The gift service knows how to:
Take instructions from an envelope
Apply them to items in boxes
Deliver the results in new boxes
For instance:
You have a box with a mug (Just mug)
You have an envelope with "add name" instructions (Just addName)
The service can combine them:
Just addName <*> Just mugYou get a box with a personalized mug (Just personalizedMug)
What makes applicatives special is you can:
Apply multi-parameter functions to multiple boxed values
For example:
liftA2 createGiftSet (Just mug) (Just chocolates)creates a gift set from two boxed items
Monads: The Travel Agency
Real-Life Example: A travel agency booking service.
Explanation:
Each booking step might succeed (Just result) or fail (Nothing)
Each step depends on the result of the previous step
If any step fails, the whole process fails
For example, booking a trip:
Check flight availability:
checkFlight "NYC"→ Just flightInfoBook hotel based on arrival:
flightInfo >>= bookHotel→ Just hotelInfoArrange transport:
hotelInfo >>= arrangeTransport→ Just tripItinerary
If the flight check returns Nothing (no flights available), the whole chain results in Nothing - no hotel booking is attempted.
The key insight: Monads allow you to sequence operations where each step:
Takes a regular value
Returns a value in a context
Depends on the success of previous steps
