Latest / CyberSecurity Summary / Mastering Functional Programming: Functional techniques for sequential and parallel programming with Scala
Transcript
- 0:00Speaker 1: You know, when we think about writing software, there's this
- 0:04Speaker 1: underlying assumption that we are totally the masters of the machine.
- 0:08Speaker 2: Right, yeah.
- 0:08Speaker 1: Like, we're the architects. And the code is just our precise,
- 0:13Speaker 1: you know, step-by-step blueprint. We tell the computer exactly what
- 0:16Speaker 1: to do, when to do it, how to do it.
- 0:18Speaker 2: It's a very comforting illusion for developers, honestly. I mean,
- 0:21Speaker 2: you give a specific instruction and the machine executes it.
- 0:24Speaker 2: Step one, step two, step three. You feel entirely in control.
- 0:28Speaker 1: But what if... What if the very way we've been
- 0:31Speaker 1: taught to write those instructions is actually making our jobs
- 0:35Speaker 1: infinitely harder?
- 0:36Speaker 2: Yeah. It's a wild thought.
- 0:37Speaker 1: Right. What if micromanaging the computer is the exact reason
- 0:41Speaker 1: our software constantly breaks?
- 0:47Speaker 2: Welcome to the Deep Dive, everyone. Today, we are pulling
- 0:49Speaker 2: from a really dense but honestly just fascinating text called
- 0:52Speaker 2: Mastering Functional Programming by Anatoly Kometchuk.
- 0:56Speaker 1: It is a phenomenal book. Dense but phenomenal. It really is.
- 0:59Speaker 1: And our mission for you today is to basically uncover
- 1:02Speaker 1: how shifting from a traditional imperative programming style to a
- 1:07Speaker 1: declarative functional one can actually eliminate entire classes of bugs.
- 1:12Speaker 2: Exactly. And it all comes down to separating what we
- 1:15Speaker 2: want a program to do from how the computer actually
- 1:19Speaker 2: pulls it off.
- 1:20Speaker 1: Right.
- 1:21Speaker 2: Because that separation, I mean, it's a massive paradigm shift.
- 1:24Speaker 2: It requires... completely rewiring how you think about logic. You
- 1:28Speaker 2: have to move away from giving commands to simply, you know,
- 1:32Speaker 2: describing facts.
- 1:34Speaker 1: I really love the analogy the book sets up for this.
- 1:36Speaker 1: It's so clear. So think of imperative programming, like going
- 1:39Speaker 1: into a restaurant kitchen and just completely micromanaging the chef. Oh, yeah.
- 1:42Speaker 2: Standing right over their shoulder.
- 1:43Speaker 1: Exactly. You're saying, OK, take the onion, put it on
- 1:46Speaker 1: the board, pick up the knife, move your hand up
- 1:48Speaker 1: and down.
- 1:49Speaker 2: Yeah.
- 1:49Speaker 1: Chop the onion. Turn on the stove to medium heat.
- 1:52Speaker 2: Which is just exhausting for you.
- 1:53Speaker 1: So exhausting. And it leaves like a hundred places where
- 1:57Speaker 1: you could give a slightly wrong instruction and completely ruin
- 1:59Speaker 1: the meal. But declarative programming, on the other hand, is
- 2:02Speaker 1: just sitting at your table in the dining room and
- 2:05Speaker 1: ordering the soup.
- 2:06Speaker 2: Yes.
- 2:06Speaker 1: You don't care how the kitchen makes it. You just
- 2:08Speaker 1: care about the end result.
- 2:10Speaker 2: And if we look at the history of computer science,
- 2:12Speaker 2: we've actually been slowly moving toward the dining room for
- 2:17Speaker 2: decades now.
- 2:18Speaker 1: Oh, really? Yeah.
- 2:19Speaker 2: The text brings up this classic historical example of The
- 2:23Speaker 2: go-to statement versus the loop.
- 2:25Speaker 1: Okay, right.
- 2:26Speaker 2: Back in the early days of programming, developers heavily relied
- 2:30Speaker 2: on go-to statements. You would literally tell the computer, run
- 2:33Speaker 2: line 10, then line 11, now go to line 84.
- 2:37Speaker 1: Which created the infamous spaghetti code.
- 2:40Speaker 2: Oh, absolutely.
- 2:40Speaker 1: I mean, I can't even imagine trying to debug a
- 2:42Speaker 1: massive program where the logic is just randomly jumping up
- 2:46Speaker 1: and down thousands of lines of text.
- 2:48Speaker 2: It was a total nightmare. Because the programmer had to
- 2:50Speaker 2: manually manage every single one of those transitions in their head.
- 2:54Speaker 1: Right.
- 2:55Speaker 2: But eventually computer scientists realized that, you know, jumping around
- 2:58Speaker 2: was usually just a repeating pattern specifically, the pattern of
- 3:01Speaker 2: doing something multiple times. Right.
- 3:03Speaker 1: So they abstracted it.
- 3:04Speaker 2: Exactly. They abstracted that pattern into foreign while loops. The
- 3:10Speaker 2: compiler took over all that messy jumping logic under the hood.
- 3:14Speaker 2: It enforced constraints so you couldn't make silly mistakes.
- 3:16Speaker 1: You just said run this block 10 times. And the
- 3:19Speaker 1: language handled the rest.
- 3:21Speaker 2: Precisely. And modern functional programming, it simply takes this exact
- 3:25Speaker 2: same idea, abstracting away repeating algorithmic patterns, and it applies
- 3:30Speaker 2: it to absolutely everything.
- 3:32Speaker 1: Which is wild, because if we've successfully abstracted loops, it
- 3:35Speaker 1: kind of makes you wonder why we stop there.
- 3:37Speaker 2: Right. Why stop at loops?
- 3:38Speaker 1: Yeah. So let's look at how we handle collections of data,
- 3:42Speaker 1: because the source compares Java, representing that older imperative style,
- 3:46Speaker 1: with Scala, which represents this declarative functional style.
- 3:50Speaker 2: That's a great comparison.
- 3:52Speaker 1: So let's say you're listening to this and you just
- 3:53Speaker 1: need to do something super simple, like filter a list
- 3:56Speaker 1: of employee names to find the ones that start with
- 3:58Speaker 1: the letter A.
- 3:59Speaker 2: Well, in Java, you are right back in that kitchen
- 4:01Speaker 2: micromanaging the chef. You have to create a brand new
- 4:05Speaker 2: empty array to hold the results. Then you write a
- 4:09Speaker 2: for loop to iterate through the original array. Inside the loop,
- 4:13Speaker 2: you write an if statement to check the first letter
- 4:16Speaker 2: of the current name.
- 4:17Speaker 1: It's so many steps.
- 4:18Speaker 2: It is. And if it matches, you manually add that
- 4:21Speaker 2: name to the new array, and then you move to
- 4:23Speaker 2: the next item.
- 4:24Speaker 1: And it feels logical to us because that's just how
- 4:26Speaker 1: we were all taught to code.
- 4:27Speaker 2: Exactly.
- 4:28Speaker 1: But the book points out this hidden trap in that
- 4:30Speaker 1: Java code. It introduces the dimension of time.
- 4:34Speaker 2: Yes, and time is the enemy of predictable software.
- 4:37Speaker 1: Wait, really? How so?
- 4:38Speaker 2: Because in that imperative Java code, you are describing a
- 4:41Speaker 2: chronological sequence of events. Step one, create the array. Step two,
- 4:46Speaker 2: look at the first item. Step three, add it. You
- 4:48Speaker 2: are constantly managing the state of the program as it
- 4:51Speaker 2: changes over time.
- 4:52Speaker 1: Oh, I see.
- 4:52Speaker 2: And because you're manually managing the creation of the array
- 4:56Speaker 2: and the insertion of the items, there is room for
- 4:58Speaker 2: human error at every single second.
- 5:00Speaker 1: Right, like what if you add the result to the
- 5:01Speaker 1: wrong collection by accident?
- 5:03Speaker 2: Or what if your loop logic is just off by
- 5:05Speaker 2: one and you skip the last employee?
- 5:07Speaker 1: Yeah, off by one errors are the worst. But then
- 5:10Speaker 1: in Scala, using the functional approach, you literally just take
- 5:13Speaker 1: the source collection and call a dot filter method.
- 5:16Speaker 2: Yep.
- 5:16Speaker 1: You just pass in, A tiny inline rule that says,
- 5:19Speaker 1: you know, name starts with A. That is it. Just
- 5:23Speaker 1: ordering the soup.
- 5:24Speaker 2: You are naming the pattern filtering and letting the language
- 5:28Speaker 2: handle the underlying algorithm entirely.
- 5:30Speaker 1: And so time is removed from the equation. Exactly.
- 5:33Speaker 2: You're no longer describing a chronological sequence. You are writing
- 5:37Speaker 2: a mathematical expression. You're declaring... This new collection is mathematically
- 5:43Speaker 2: equivalent to the old collection, just filtered by this rule.
- 5:47Speaker 1: So you completely ignore the underlying engine doing the work.
- 5:49Speaker 2: Right. You shift from algorithmic reasoning to algebraic reasoning.
- 5:53Speaker 1: Okay. Here's where it gets really interesting, though. I want
- 5:55Speaker 1: to push back a little. Okay.
- 5:56Speaker 2: Let's hear it.
- 5:57Speaker 1: If everything is just math and algebraic expressions, what happens
- 6:01Speaker 1: to the whole concept of a function?
- 6:03Speaker 2: Good question.
- 6:03Speaker 1: Because, I mean, if you're coming from object-oriented programming or OOP,
- 6:08Speaker 1: a function is a behavior.
- 6:10Speaker 2: Right.
- 6:11Speaker 1: It's attached to an object, like a user or a
- 6:13Speaker 1: shopping cart, and it changes things inside that object.
- 6:16Speaker 2: Yeah, functional programming completely tears down that definition. Wow. It
- 6:20Speaker 2: strips away the idea of behavior and replaces it with
- 6:23Speaker 2: pure mathematical computation.
- 6:24Speaker 1: Okay, let's use the soda machine example from the text
- 6:27Speaker 1: to make this concrete, because that helped me a lot.
- 6:28Speaker 2: Perfect example.
- 6:29Speaker 1: In standard OOP, you'd have a soda machine object, and
- 6:32Speaker 1: it has mutable state, meaning its internal data can change.
- 6:37Speaker 1: It tracks how many coins are currently inside and how
- 6:39Speaker 1: many cans of soda are left. Right. When you call
- 6:42Speaker 1: the insert coin function, it changes the machine's internal state.
- 6:45Speaker 1: It increments the coins by one, decrements the cans by one,
- 6:49Speaker 1: and spits out a soda.
- 6:51Speaker 2: And in the functional world, modifying that state is considered
- 6:54Speaker 2: a severe anti-pattern.
- 6:56Speaker 1: A severe anti-pattern.
- 6:57Speaker 2: Absolutely. It's called a side effect. The function is modifying
- 7:01Speaker 2: an environment outside of its own body. Functional programming dictates
- 7:05Speaker 2: that functions should be pure. Pure.
- 7:08Speaker 1: Meaning what exactly?
- 7:09Speaker 2: They should not change anything in the outside world, and
- 7:11Speaker 2: they should always return the exact same output for a
- 7:14Speaker 2: given input.
- 7:15Speaker 1: I remember reading that and just thinking, how do you
- 7:18Speaker 1: buy a soda without changing the machine?
- 7:21Speaker 2: By never changing the machine.
- 7:23Speaker 1: What? Yeah.
- 7:24Speaker 2: In the pure functional version, the insert coin function does
- 7:27Speaker 2: not modify the original soda machine object at all. Instead,
- 7:31Speaker 2: it takes the current state of the machine as an input,
- 7:34Speaker 2: and it returns two things. The soda can you just
- 7:37Speaker 2: bought and a brand new, completely separate soda machine object
- 7:42Speaker 2: that reflects the new state.
- 7:43Speaker 1: That's wild. So the original machine remains totally untouched.
- 7:46Speaker 2: It's immutable, yes.
- 7:48Speaker 1: Now, if you're listening and thinking, wait, isn't that horribly inefficient?
- 7:51Speaker 1: Creating a whole new machine in memory every single time
- 7:54Speaker 1: someone buys a soda. I had the exact same thought.
- 7:56Speaker 1: I mean, won't the computer just run out of memory instantly?
- 7:59Speaker 2: It definitely sounds like a memory leak waiting to happen.
- 8:02Speaker 2: But it's not, thanks to this clever concept called structural sharing.
- 8:05Speaker 1: Structural sharing. Yeah.
- 8:07Speaker 2: Yeah. Under the hood, functional languages don't actually copy all
- 8:11Speaker 2: the data. Think of it kind of like a family tree.
- 8:14Speaker 1: Okay.
- 8:14Speaker 2: If you add a new cousin to the tree, you
- 8:17Speaker 2: don't rewrite the entire history of the grandparents and great grandparents, right? Right.
- 8:22Speaker 1: You just add the cousin. Exactly.
- 8:24Speaker 2: You just create a new node for the cousin that
- 8:26Speaker 2: points back to the existing family structure. The original tree
- 8:29Speaker 2: still exists exactly as it was for anyone looking at it.
- 8:32Speaker 2: And the new tree shares like 99% of the same memory.
- 8:36Speaker 1: Okay, that makes so much sense. It's actually highly efficient.
- 8:39Speaker 1: But what is the actual payoff for doing this? Like
- 8:42Speaker 1: why jump through all these hoops just to avoid changing
- 8:45Speaker 1: the original object?
- 8:46Speaker 2: The ultimate payoff is thread safety. Ah. The text illustrates
- 8:50Speaker 2: this beautifully with a multiplayer game state example.
- 8:54Speaker 1: Oh, I love this part.
- 8:55Speaker 2: Right. Imagine you have a mutable list tracking users currently
- 8:59Speaker 2: online in a game. Now imagine you have a background
- 9:02Speaker 2: process running called reward winners. It starts reading that mutable
- 9:06Speaker 2: list to find out who gets a prize.
- 9:07Speaker 1: But while that reward process is like halfway through reading
- 9:11Speaker 1: the list, another player decides to log out and the
- 9:14Speaker 1: game server removes that player from the mutable list.
- 9:17Speaker 2: Suddenly the ground just shifts beneath the reward process. The
- 9:21Speaker 2: game crashes or the reward logic fails because the state
- 9:25Speaker 2: was changed out from under the thread that was trying
- 9:27Speaker 2: to read it.
- 9:28Speaker 1: Which is a classic race condition.
- 9:29Speaker 2: Exactly. And to prevent it in imperative programming, you have
- 9:33Speaker 2: to use complex locks, pausing other parts of your app
- 9:37Speaker 2: so they don't step on each other's toes.
- 9:38Speaker 1: Which is notoriously hard to debug.
- 9:41Speaker 2: It is a nightmare. But if that list of users
- 9:44Speaker 2: was immutable, if it could never be changed once created,
- 9:48Speaker 2: then any process can safely read it at any time.
- 9:51Speaker 1: Because it's locked in time.
- 9:52Speaker 2: Yes. If a user logs out, the system just computes
- 9:55Speaker 2: a new separate list for future operations. The old list
- 9:59Speaker 2: stays perfectly valid in memory for the reward thread that's
- 10:02Speaker 2: currently looking at it.
- 10:03Speaker 1: So you get thread safety basically for free without writing
- 10:06Speaker 1: a single lock.
- 10:07Speaker 2: It solves massive, massive scaling problems. But I will admit
- 10:11Speaker 2: it does introduce a rather large elegant in the room. Right.
- 10:14Speaker 1: Because, OK, let's unpack this. If my program is just
- 10:17Speaker 1: computing new data trees over and over, never actually changing
- 10:20Speaker 1: the outside world, how does it talk to a database?
- 10:23Speaker 2: Right.
- 10:24Speaker 1: How does it write to a file or, you know,
- 10:25Speaker 1: send an email? It can't just be a space heater
- 10:28Speaker 1: sitting in a corner crunching math.
- 10:30Speaker 2: No, it can't. And this leads to one of the
- 10:31Speaker 2: most profound philosophical concepts in the entire book. The author
- 10:35Speaker 2: argues that programmers are actually constantly dealing with two entirely
- 10:40Speaker 2: separate realities, often at the exact same time.
- 10:42Speaker 1: The first order and second order reality.
- 10:44Speaker 2: Yes. The first order reality is your business domain. It's
- 10:47Speaker 2: the pure logic. Right. It's the rules for running a warehouse,
- 10:51Speaker 2: dividing numbers, or calculating a shopping cart total. It's the
- 10:55Speaker 2: pristine math that the business owner actually cares about.
- 10:59Speaker 1: But the business owner doesn't care about the second order reality.
- 11:01Speaker 1: Not at all.
- 11:01Speaker 2: They don't even know it exists. The second order reality
- 11:04Speaker 2: is the messy technical programming environment. It's the reality of
- 11:08Speaker 2: network delays, missing database entries, full hard drives, or a
- 11:12Speaker 2: user trying to divide a number by zero.
- 11:15Speaker 1: And if you've ever spent like three hours pulling your
- 11:18Speaker 1: hair out, hunting down a null pointer exception, you know
- 11:21Speaker 1: exactly how painful that second order reality is.
- 11:24Speaker 2: Oh, absolutely.
- 11:25Speaker 1: The traditional flawed approach is to mix these two realities together.
- 11:29Speaker 1: Like if you search for a user ID in a
- 11:31Speaker 1: database and it's not there, imperative languages often just return
- 11:35Speaker 1: a null value.
- 11:36Speaker 2: Right.
- 11:37Speaker 1: Or if you divide by zero, they throw an exception
- 11:40Speaker 1: that completely halts the program.
- 11:41Speaker 2: Which puts a massive mental load on you, the programmer.
- 11:45Speaker 2: If a function might return null or might throw an exception,
- 11:48Speaker 2: the compiler usually doesn't warn you at all.
- 11:50Speaker 1: No, it doesn't.
- 11:51Speaker 2: You just have to magically remember to write if null
- 11:53Speaker 2: checks or try catch blocks everywhere. And if you forget
- 11:56Speaker 2: even once, the app blows up at runtime for the user.
- 11:59Speaker 1: So how does functional programming handle this second order reality
- 12:03Speaker 1: without breaking the pure side effect-free math of the first
- 12:07Speaker 1: order reality?
- 12:08Speaker 2: By turning phenomena into data.
- 12:10Speaker 1: Okay, tell me more.
- 12:11Speaker 2: The technical term the book uses is reification.
- 12:14Speaker 1: Reification, basically boxing reality up into effect types.
- 12:17Speaker 2: Yeah.
- 12:18Speaker 1: So instead of performing a side effect, you return a
- 12:20Speaker 1: data structure that represents the side effect.
- 12:23Speaker 2: You nailed it. Let's look at errors, for example. Instead
- 12:26Speaker 2: of throwing a division by zero exception... A pure function
- 12:30Speaker 2: will return an effect type called a try.
- 12:33Speaker 1: A try?
- 12:33Speaker 2: Yes. A try is literally a box. Inside that box,
- 12:37Speaker 2: it holds either a successful value or an exception.
- 12:41Speaker 1: Okay.
- 12:41Speaker 2: Alternatively, there's the either type, which is similar but holds
- 12:45Speaker 2: two arbitrary types by convention, a left containing the error
- 12:49Speaker 2: string and a right containing the successful result.
- 12:52Speaker 1: So if you divide 4 by 2, it turns a
- 12:55Speaker 1: box labeled right with a 2 inside.
- 12:58Speaker 2: Yes.
- 12:58Speaker 1: But if you divide by zero, it doesn't crash the app.
- 13:00Speaker 1: It just returns a box labeled left with a string
- 13:03Speaker 1: inside that says, you know, division by zero.
- 13:05Speaker 2: Exactly. And this applies to time and delays, too.
- 13:08Speaker 1: Oh, right. The weather app example.
- 13:09Speaker 2: Yes, that's a perfect one.
- 13:10Speaker 1: Say you need to hit a weather API to warn
- 13:13Speaker 1: a user about rain. Reaching out over the internet takes time.
- 13:16Speaker 1: You shouldn't freeze the entire application waiting for the weather
- 13:19Speaker 1: server to respond.
- 13:20Speaker 2: No, that would be terrible UX.
- 13:22Speaker 1: Right. In the old days, you'd use messy callbacks like,
- 13:25Speaker 1: When this data finally arrives, go run this other chunk
- 13:27Speaker 1: of code, which just quickly turns into unreadable callback hell.
- 13:31Speaker 1: It does.
- 13:32Speaker 2: But in the functional paradigm, we use another effect type
- 13:35Speaker 2: called a future. A future. It's a box that represents
- 13:39Speaker 2: an asynchronous delay. The function immediately returns the box, keeping
- 13:43Speaker 2: your application running smoothly. And eventually the box fills with
- 13:46Speaker 2: the weather data once the network request actually finishes.
- 13:49Speaker 1: The book also mentions the reader type for handling dependencies
- 13:52Speaker 1: like database connections, right?
- 13:54Speaker 2: Yes, the reader type.
- 13:55Speaker 1: So instead of passing a database connection through every single
- 13:58Speaker 1: function like a relay baton, Reader acts as an effect
- 14:01Speaker 1: that basically says, I am a computation that is paused.
- 14:04Speaker 1: I cannot run until you hand me a database connection. Exactly.
- 14:08Speaker 2: All of these try, either future Reader, they are effect types.
- 14:14Speaker 2: They encapsulate the messy second-order reality of errors, delays, and
- 14:18Speaker 2: dependencies into neat, manageable boxes of data.
- 14:22Speaker 1: Now, if you're listening and thinking this sounds like way
- 14:24Speaker 1: more work just to avoid writing an if statement, I
- 14:27Speaker 1: am right there with you.
- 14:28Speaker 2: It can seem that way at first.
- 14:30Speaker 1: But here is the magic trick. And this is what
- 14:32Speaker 1: really blew my mind. By wrapping these messy realities in
- 14:35Speaker 1: these boxes, the compiler forces you to handle them.
- 14:39Speaker 2: Yes.
- 14:40Speaker 1: You physically cannot get the number out of the try
- 14:42Speaker 1: box or the future box without explicitly writing code to
- 14:46Speaker 1: handle the error case or the delay. The mental load
- 14:49Speaker 1: just vanishes.
- 14:50Speaker 2: It completely vanishes.
- 14:51Speaker 1: You don't have to memorize which functions throw exceptions. The
- 14:55Speaker 1: return type explicitly tells you what reality you're dealing with.
- 14:58Speaker 2: It creates incredibly robust software. But, as you might guess,
- 15:02Speaker 2: it does create a new mechanical problem for the developer.
- 15:05Speaker 1: Right, because, well, if every single action I take returns
- 15:09Speaker 1: a new box, won't my code just look like a
- 15:11Speaker 1: giant set of Russian nesting dolls? If step one returns
- 15:15Speaker 1: a try box... And step two needs the data inside
- 15:18Speaker 1: that box. How do I actually string computations together without
- 15:22Speaker 1: writing awful spaghetti code to constantly unpack them?
- 15:25Speaker 2: Well, you need specialized tools to work with these boxes.
- 15:27Speaker 2: In functional programming, we use two fundamental operations, map and
- 15:31Speaker 2: flat map.
- 15:32Speaker 1: Okay, let's break those down. How does map work?
- 15:35Speaker 2: Map is kind of like a drone delivery that can
- 15:37Speaker 2: reach inside the box. If you have a normal function
- 15:40Speaker 2: that multiplies a number by two, and you have a
- 15:43Speaker 2: number currently trapped inside a try box, Map lets you
- 15:46Speaker 2: send that multiplication function inside the box.
- 15:49Speaker 1: So the box stays closed.
- 15:50Speaker 2: Exactly. It multiplies the number and leaves the new results
- 15:54Speaker 2: safely inside the box. You never had to open it yourself.
- 15:57Speaker 1: Got it. So Map works perfectly when the function I'm
- 16:00Speaker 1: applying is just normal, first-order math.
- 16:03Speaker 2: Yes.
- 16:04Speaker 1: But what if my second step also interacts with the
- 16:07Speaker 1: second-order reality?
- 16:08Speaker 2: Oh.
- 16:08Speaker 1: Like, let's go back to the Weather app. Step 1
- 16:11Speaker 1: calls the Weather API and returns a future box. Step
- 16:15Speaker 1: two needs to take that weather data and call a
- 16:17Speaker 1: calendar API to reschedule an event. Calling the calendar API
- 16:22Speaker 1: also returns a future box.
- 16:23Speaker 2: Right.
- 16:24Speaker 1: If I use map, don't I end up with a
- 16:25Speaker 1: calendar future trapped inside a weather future? Like literally a
- 16:29Speaker 1: box inside a box?
- 16:30Speaker 2: You would. And that is exactly why we have FlatMap.
- 16:33Speaker 1: Okay.
- 16:33Speaker 2: FlatMap is specifically designed for sequentially chaining two box-producing functions together.
- 16:38Speaker 2: Think of FlatMap like a railway switch.
- 16:40Speaker 1: A railway switch?
- 16:41Speaker 2: Yes. Your data is a train moving along a track.
- 16:45Speaker 2: Step one runs. If it succeeds, the switch routes the
- 16:49Speaker 2: data smoothly onto the track for step two, merging them
- 16:52Speaker 2: so you don't get messed in boxes.
- 16:53Speaker 1: Oh, nice.
- 16:54Speaker 2: But if step one fails, say the weather API just
- 16:57Speaker 2: goes down the switch, instantly diverts the train onto the
- 17:00Speaker 2: error track, step two is bypassed completely.
- 17:03Speaker 1: So it flattens the result. I can just say do
- 17:05Speaker 1: step one. If it succeeds, feed it into step two.
- 17:08Speaker 1: If step one fails... just short circuit the whole process
- 17:11Speaker 1: and return the failure. And I don't have to write
- 17:13Speaker 1: a single nested if statement to do that.
- 17:15Speaker 2: Not a single one. And in the Scala ecosystem, these
- 17:19Speaker 2: toolboxes for working with effect types are called type classes.
- 17:23Speaker 2: The book spends a lot of time on a really
- 17:24Speaker 2: famous Scala library called CATS.
- 17:27Speaker 1: Yeah, the CATS library is fascinating because it doesn't force
- 17:30Speaker 1: you to rewrite the core Scala language. It cleverly injects
- 17:34Speaker 1: these tools like map and flat map Onto standard data structures.
- 17:37Speaker 2: Right.
- 17:38Speaker 1: It completely separates the boxes themselves from the behavior used
- 17:42Speaker 1: to manipulate them.
- 17:43Speaker 2: And the most famous, perhaps most feared, type class in
- 17:46Speaker 2: that library is the monad.
- 17:48Speaker 1: Ugh, the M word. Monads have this huge reputation for
- 17:52Speaker 1: being completely impossible to understand.
- 17:54Speaker 2: They really do. But a monad is simply the toolbox
- 17:58Speaker 2: for sequential composition.
- 17:59Speaker 1: Okay.
- 18:00Speaker 2: If you need to run computation A... and then use
- 18:03Speaker 2: its result to run computation B, you need a monad.
- 18:06Speaker 2: It's what provides that flat map railway switch we just
- 18:09Speaker 2: talked about.
- 18:09Speaker 1: But a monad isn't just a random collection of methods, right?
- 18:12Speaker 2: Yeah.
- 18:12Speaker 1: To actually be a monad, it has to follow strict
- 18:15Speaker 1: mathematical laws to guarantee it's safe.
- 18:17Speaker 2: Yes, three specific laws. Left identity, right identity, and associativity.
- 18:21Speaker 1: Okay, hold on. You're losing me a bit with the
- 18:23Speaker 1: textbook terms here. What does left and right identity actually
- 18:26Speaker 1: mean for me sitting at my keyboard?
- 18:28Speaker 2: It simply means the box itself doesn't sneak in any
- 18:31Speaker 2: hidden logic. If you take a raw value and put
- 18:34Speaker 2: it into a monad box and then immediately flat map
- 18:37Speaker 2: it with a function, it should be the exact same
- 18:39Speaker 2: as just calling the function on the raw value in
- 18:41Speaker 2: the first place. The box acts purely as a container.
- 18:44Speaker 1: Okay, so it's transparent. It doesn't magically alter my data
- 18:47Speaker 1: just by putting it inside.
- 18:48Speaker 2: Exactly.
- 18:49Speaker 1: What about associativity?
- 18:51Speaker 2: Associativity just means the grouping of your operations doesn't matter.
- 18:54Speaker 2: A chained to B and then chained to C... produces
- 18:58Speaker 2: the exact same result as A chained to the combined
- 19:01Speaker 2: result of.
- 19:01Speaker 1: B and C. Kind of like basic addition.
- 19:03Speaker 2: Exactly. Think of how addition works in math. 1 plus
- 19:07Speaker 2: 2 plus 3. It doesn't matter where you put the parentheses. Wait.
- 19:10Speaker 1: If grouping doesn't matter, that means I can safely refactor
- 19:13Speaker 1: my code.
- 19:14Speaker 2: Yes.
- 19:15Speaker 1: I could chop a massive 500-line chain of operations into
- 19:18Speaker 1: three smaller readable helper functions, and I don't have to
- 19:22Speaker 1: worry about accidentally breaking the application's logic.
- 19:24Speaker 2: Precisely. The laws guarantee that refactoring is safe. If a
- 19:28Speaker 2: type class obeys those laws, it's a monad. It gives
- 19:31Speaker 2: you flat map, it gives you a way to put
- 19:33Speaker 2: raw values into a box, and it gives you a
- 19:35Speaker 2: safe way to loop recursive functions without crashing the program's memory.
- 19:39Speaker 1: But you have a critical warning about monads, right?
- 19:41Speaker 2: Yeah.
- 19:41Speaker 1: Because they're designed for sequential execution.
- 19:44Speaker 2: Yes, this is really important. In the CAPS library hierarchy,
- 19:48Speaker 2: monad actually inherits from another type class called applicative.
- 19:52Speaker 1: Let's define applicative real quick. That's the toolbox used for
- 19:54Speaker 1: parallel computations, right? When you want to run two things
- 19:57Speaker 1: at the exact same time. Exactly.
- 19:59Speaker 2: So because monad inherits from applicative, it technically has the
- 20:03Speaker 2: methods for parallel execution. Right. But here is the catch.
- 20:07Speaker 2: Because of the very nature of what a monad is,
- 20:10Speaker 2: a tool for step-by-step sequential execution, it might trick you.
- 20:15Speaker 1: Trick you how?
- 20:16Speaker 2: It might implement that parallel operation sequentially under the hood.
- 20:19Speaker 1: Whoa. So I might write code thinking I'm hitting the
- 20:23Speaker 1: weather API and the calendar API at the exact same
- 20:26Speaker 1: time to save the user a few seconds. But the
- 20:29Speaker 1: monad is secretly waiting for the weather request to finish immediately.
- 20:32Speaker 1: Before it even starts the calendar request.
- 20:34Speaker 2: Yes. You have to know which tool you are pulling
- 20:37Speaker 2: from the box. If you want true parallel execution, you
- 20:40Speaker 2: must depend on the applicative type class directly, not the monad.
- 20:44Speaker 1: Wow.
- 20:45Speaker 2: It is a subtle but critical distinction that separates OKCode
- 20:48Speaker 2: from truly high-performance software.
- 20:50Speaker 1: That is wild. OK, let's take a breath and summarize
- 20:53Speaker 1: this journey because we covered a lot of ground today.
- 20:55Speaker 2: We really did.
- 20:56Speaker 1: We started with the old days of micromanaging code with
- 20:58Speaker 1: go-to statements and messy Java loops. Then we leveled up
- 21:02Speaker 1: to declarative collections, using pure algebraic functions like dot filter
- 21:07Speaker 1: that completely removed the concept of time and human error.
- 21:10Speaker 2: Then we redefined functions entirely.
- 21:12Speaker 1: Right.
- 21:12Speaker 2: We stripped away mutable behavior to ensure thread safety, meaning
- 21:17Speaker 2: multiple parts of a program can read data without stepping.
- 21:20Speaker 1: On each other. From there, we acknowledged the chaos of
- 21:23Speaker 1: the real world, the second-order reality of errors, null values,
- 21:27Speaker 1: and network delays. But instead of letting that chaos infect
- 21:30Speaker 1: our pure business logic, We boxed it up into effect
- 21:33Speaker 1: types like try and future. Yep. And finally, we learned
- 21:36Speaker 1: how to manipulate those boxes using type classes like monads,
- 21:40Speaker 1: ensuring we can safely string everything together like railway tracks.
- 21:43Speaker 2: It is a comprehensive mathematical system for managing the complexity
- 21:46Speaker 2: of modern software.
- 21:48Speaker 1: It really is. And that leaves me with a final
- 21:50Speaker 1: provocative thought for you to mull over. If functional programming
- 21:54Speaker 1: successfully and completely isolates the business reality from the technical reality,
- 22:00Speaker 1: what does that mean for the future of our jobs?
- 22:02Speaker 2: That's the big question.
- 22:03Speaker 1: Imagine a world where non-programmers only ever have to map
- 22:07Speaker 1: out the pure algebraic logic of a business. And the compiler,
- 22:12Speaker 1: or maybe an AI, perfectly handles 100% of the side effects,
- 22:16Speaker 1: the threading, the errors, and the memory management under the hood.
- 22:20Speaker 2: Wow.
- 22:21Speaker 1: Could the act of writing code as we know it
- 22:23Speaker 1: today eventually become obsolete, replaced entirely by just writing pure
- 22:28Speaker 1: mathematical rules?
- 22:29Speaker 2: It's entirely possible. I mean... Once that messy second-order reality
- 22:33Speaker 2: is fully automated, the role of the developer changes from
- 22:35Speaker 2: typing instructions to architecting logic.
- 22:38Speaker 1: We might just get to sit at the table and
- 22:40Speaker 1: order the soup and never have to micromanage the chef
- 22:42Speaker 1: ever again.
- 22:43Speaker 2: I wouldn't mind that at all.
- 22:44Speaker 1: Thanks for joining us on this deep dive. Tomorrow, when
- 22:46Speaker 1: you look at your code base, try to spot those
- 22:49Speaker 1: first and second-order realities. See if you can spot where
- 22:52Speaker 1: you're just chopping onions when you really should just be
- 22:54Speaker 1: asking for the soup. Catch you next time.