Latest / CyberSecurity Summary / Functional Programming in Scala, Second Edition
Transcript
- 0:00Speaker 1: Have you ever looked at a massive code base, like
- 0:04Speaker 1: maybe when you inherited from a different team, or honestly
- 0:08Speaker 1: even when you wrote yourself six months ago, and you
- 0:10Speaker 1: just felt like it was this incredibly fragile house of cards.
- 0:14Speaker 2: Oh yeah, I mean it is a universally terrifying feeling
- 0:17Speaker 2: for anyone who writes software.
- 0:18Speaker 1: Right, you get a ticket to update I don't know,
- 0:21Speaker 1: simple user profile field, You make the change, and somehow
- 0:25Speaker 1: completely inexplicably, the payment processing system just goes down in production.
- 0:30Speaker 2: Yeah, and you realize that the different components of your
- 0:32Speaker 2: system are just so deeply entangled, like they're sharing state
- 0:36Speaker 2: modifying data behind the scenes, so you can literally no
- 0:39Speaker 2: longer predict what a single line of code is actually
- 0:41Speaker 2: going to do to the broader application exactly.
- 0:44Speaker 1: And that fear, you know, that fear of breathing too
- 0:46Speaker 1: hard on the keyboard, is exactly what we are tackling today.
- 0:49Speaker 1: So welcome to another deep dive.
- 0:51Speaker 2: Glad to be here.
- 0:52Speaker 1: Our mission today is to really help you understand a
- 0:55Speaker 1: radical premise that solves this exact problem of tangled fragile CD.
- 1:00Speaker 1: We are diving into the world of functional programming and
- 1:04Speaker 1: we're drawing our insights directly from the foundational text Functional
- 1:07Speaker 1: Programming in Skala by Paul Cisano and Runer Janisson.
- 1:11Speaker 2: Yeah, and it's such a remarkable book because it transcends
- 1:16Speaker 2: just teaching a specific programming language. It fundamentally forces you
- 1:20Speaker 2: to adopt a completely different paradigm for reasoning about software architecture.
- 1:25Speaker 1: Definitely, and we are going to like strip away the
- 1:29Speaker 1: intimidating academic jargon that usually surrounds this.
- 1:32Speaker 2: Whole topic, which is definitely needed. The jargon can be
- 1:35Speaker 2: a lot totally.
- 1:35Speaker 1: We're going to uncover exactly what pure functions are, how
- 1:38Speaker 1: they mechanically change the way we write code, and why
- 1:40Speaker 1: abandoning the things we've always relied on, like modifying variables
- 1:43Speaker 1: in place, actually gives you significantly more power, testability and modularity, which.
- 1:48Speaker 2: I mean often sounds wildly counterintuitive to developers trained in
- 1:51Speaker 2: standard object oriented or imperative styles. The immediate reaction is
- 1:55Speaker 2: usually how can I possibly write a useful application if
- 1:59Speaker 2: I am physically constrain from changing the state of anything.
- 2:02Speaker 1: Yeah, it sounds impossible at first.
- 2:04Speaker 2: It does, but as we'll see, that rigid constraint is
- 2:08Speaker 2: exactly the engine that drives modularity.
- 2:10Speaker 1: Okay, let's unpack this with a very practical real world
- 2:14Speaker 1: scenario from the text, because jumping straight into abstract math
- 2:18Speaker 1: is just the fastest way to lose.
- 2:20Speaker 2: The plot completely. Agree, let's ground it.
- 2:22Speaker 1: So we need to define the absolute core rule of
- 2:25Speaker 1: functional programming, which is no side effects. And the authors
- 2:28Speaker 1: actually start us off in a coffee shop.
- 2:30Speaker 2: Ah, yes, the classic buy coffee example. Yes. So, if
- 2:34Speaker 2: you are writing a standard imperative program for a point
- 2:37Speaker 2: of sale system, you might write a function called buy
- 2:40Speaker 2: coffee and inside that function block you instance, she ate
- 2:43Speaker 2: a new cup of coffee, and then you invariably have
- 2:45Speaker 2: a line of code that looks something like you know,
- 2:47Speaker 2: cc dot charge and then cup dout price.
- 2:51Speaker 1: Which from a purely sequential perspective seems completely logical. Right,
- 2:54Speaker 1: The customer buys the coffee, so the function tells the
- 2:57Speaker 1: credit card object to charge the card. Right, But that
- 3:01Speaker 1: cc dot charge line represents a side effect exactly, and
- 3:04Speaker 1: mechanically speaking, a side effect is when a function does
- 3:07Speaker 1: literally anything other than compute and return a result, like
- 3:12Speaker 1: in this case, reaching out to an external payment gateway,
- 3:16Speaker 1: or modifying a bank balance, or even just writing a
- 3:20Speaker 1: log to a database, and.
- 3:21Speaker 2: The authors expertly point out the massive architectural headache this creates,
- 3:25Speaker 2: starting basically with testing.
- 3:27Speaker 1: Oh, testing is a nightmare with this.
- 3:29Speaker 2: It is because if you want to write an automated
- 3:31Speaker 2: unit test for your bi cooffee logic, you cannot have
- 3:35Speaker 2: your test suite actually paying visa and drain a real
- 3:38Speaker 2: bank account every single time the CICD pipeline runs.
- 3:41Speaker 1: Yeah, obviously that would be very bad. So you're forced
- 3:44Speaker 1: to invent these complex, brittle mock objects, right.
- 3:47Speaker 2: Yep, exactly.
- 3:48Speaker 1: You have to use dependency injection to pass in a
- 3:50Speaker 1: fake credit card interface just to trick your own function
- 3:53Speaker 1: into running safely, all just to verify that a customer
- 3:56Speaker 1: can buy a coffee. It's an enormous amount.
- 3:58Speaker 2: Of overhead, it really is.
- 3:59Speaker 1: The text makes a really compelling case that testing isn't
- 4:02Speaker 1: even the fatal flaw here. It's actually reusability. Right.
- 4:06Speaker 2: Think about the business logic for a second. Imagine a customer, Alice,
- 4:10Speaker 2: walks into the shop and orders twelve coffees for her
- 4:13Speaker 2: entire office. Okay, if you want to reuse your existing
- 4:17Speaker 2: buy coffee function, your only real option in an imperative
- 4:20Speaker 2: system is to put it inside a loop that iterates
- 4:23Speaker 2: twelve times.
- 4:24Speaker 1: Oh wow, which means your application is going to reach
- 4:27Speaker 1: out over the network to the payment gateway twelve separate times.
- 4:31Speaker 2: Exactly.
- 4:32Speaker 1: You are authorizing twelve individual microtransactions and incurring twelve separate
- 4:36Speaker 1: processing fees for a single.
- 4:38Speaker 2: Order, which is just a complete architectural failure.
- 4:41Speaker 1: Yeah. That's terrible. So how does functional programming solve this?
- 4:45Speaker 1: It solves it by eliminating the site effect entirely, right, Yes.
- 4:48Speaker 2: The functional implementation of buy coffee does not charge the
- 4:52Speaker 2: cart at all.
- 4:53Speaker 1: Wait, really, it just doesn't charge it.
- 4:55Speaker 2: Nope. Instead, it computes and returns two things, the coffee
- 4:59Speaker 2: itself and a brand new charge data object that just
- 5:02Speaker 2: represents the transaction.
- 5:04Speaker 1: What's fascinating here is how this seemingly minor tweak completely
- 5:08Speaker 1: shifts your system's architecture.
- 5:10Speaker 2: It's massive. We are strictly separating the creation of a
- 5:15Speaker 2: charge from the interpretation, or like, the actual execution of
- 5:19Speaker 2: that charge by returning the charge as a mere value,
- 5:22Speaker 2: just data in memory. The function hasn't mutated the outside
- 5:25Speaker 2: world yet.
- 5:26Speaker 1: So I like to visualize it as getting a stack
- 5:29Speaker 1: of physical paper receipts.
- 5:31Speaker 2: Oh, that's a great way to look at it.
- 5:32Speaker 1: Right, Instead of swiping your card and draining your bank
- 5:34Speaker 1: account the second you take a sip of coffee, the
- 5:37Speaker 1: pure function just hands your receipt exactly and later in
- 5:40Speaker 1: the application flow, you can gather all twelve receipts for
- 5:43Speaker 1: Alice's order and pass them to a completely different function,
- 5:47Speaker 1: maybe something called a coalesce, which batches those receipts by
- 5:51Speaker 1: credit card number, adds up the total, and processes one
- 5:55Speaker 1: single combined payment to the external gateway.
- 5:58Speaker 2: That receipt analogy captures the mechanism perfectly. Thanks, And if
- 6:02Speaker 2: we connect this to the bigger picture of system design,
- 6:05Speaker 2: this is really the holy grail of functional architecture. You
- 6:09Speaker 2: strive to build applications with a pure core. A pure core, yeah,
- 6:13Speaker 2: and that core contains all your complex, highly testable business logic,
- 6:18Speaker 2: like batching those receipts and calculating totals. Then you push
- 6:22Speaker 2: all the side effects to a very thin, isolated layer
- 6:26Speaker 2: on the absolute outer edge of your application that actually
- 6:29Speaker 2: talks to the database or the bank.
- 6:31Speaker 1: Okay, so we've delayed the execution of the side effect.
- 6:33Speaker 1: But what does this mean mathematically? The authors attribute this
- 6:37Speaker 1: capability to a foundational property called referential transparency or RT right.
- 6:43Speaker 2: Referential transparency is the architectural guarantee that makes this whole
- 6:47Speaker 2: paradigm function okay. In mechanical terms, it means that evaluating
- 6:51Speaker 2: an expression doesn't secretly change the state of the world
- 6:54Speaker 2: around it. A function called is mathematically and practically equivalent
- 6:58Speaker 2: to its return value.
- 6:59Speaker 1: So what is this that's all mean? Like to ground this,
- 7:02Speaker 1: the book contrasts two standard data types you'd find in
- 7:05Speaker 1: Java or Scala to show where this property holds up
- 7:08Speaker 1: and where it completely collapses.
- 7:09Speaker 2: Yeah, they compare the standard immutable string with the mutable
- 7:12Speaker 2: string builder class. So if you have an immutable string,
- 7:15Speaker 2: let's say variable x equals hello, and you append the
- 7:18Speaker 2: word world to it, the compiler gives you a brand
- 7:22Speaker 2: new string, a completely new one, exactly the original variable
- 7:25Speaker 2: x remains perfectly untouched. The operation is referentially transparent.
- 7:31Speaker 1: But if you use string builder, which is designed to
- 7:33Speaker 1: be mutated in place for performance reasons, and you call
- 7:36Speaker 1: it a pend method, it physically alters the existing object
- 7:39Speaker 1: in memory, like it destroys the previous state.
- 7:42Speaker 2: And that destroys referential transparency.
- 7:45Speaker 1: Yeah.
- 7:46Speaker 2: Imagine you have a variable y pointing to a string builder.
- 7:49Speaker 2: If you substitute the expression y dot append a into
- 7:53Speaker 2: two different places in your application logic, you will get
- 7:57Speaker 2: drastically different results.
- 7:58Speaker 1: Because the first call mutated underlying state exactly.
- 8:01Speaker 2: So the second call is now operating on a corrupted,
- 8:04Speaker 2: fundamentally different object.
- 8:05Speaker 1: Okay, I see the appeal of local reasoning. But here's
- 8:07Speaker 1: where it gets really interesting for me, and I have
- 8:09Speaker 1: to push back a bit.
- 8:10Speaker 2: Sure, go ahead.
- 8:11Speaker 1: If we are locked inside this pure core, right, this
- 8:15Speaker 1: sterile pipeline, where we are physically forbidden from mutating standard
- 8:19Speaker 1: state variables, how do we actually compute anything?
- 8:22Speaker 2: That is the big question.
- 8:24Speaker 1: I mean, we can't even write a standard WI loop
- 8:26Speaker 1: with a counter variable that increments because incrementing mutates the counter.
- 8:30Speaker 1: Aren't we just making our jobs exponentially harder for the
- 8:33Speaker 1: sake of mathematical theory.
- 8:35Speaker 2: It is honestly the most common friction point for developers
- 8:38Speaker 2: transitioning to this style. But the payoff is that concept
- 8:42Speaker 2: of local reasoning. Okay, when your functions are completely pure,
- 8:46Speaker 2: they act as sealed black boxes. Contamination from one part
- 8:49Speaker 2: of the app literally cannot physically leak into another.
- 8:52Speaker 1: Because there's no shared mutable state exactly.
- 8:55Speaker 2: You never have to mentally simulate the state of the
- 8:57Speaker 2: entire system to understand a single function. Yeah, you pass
- 9:00Speaker 2: data in, you get data.
- 9:02Speaker 1: Out, simple as that.
- 9:03Speaker 2: But to answer your question about how we actually iterate
- 9:05Speaker 2: without mutable counters, we have to leverage recursion, right.
- 9:09Speaker 1: So instead of a wild loop that mutates a local variable,
- 9:12Speaker 1: the text shows how to implement tail recursive functions. You
- 9:15Speaker 1: write a local helper function, usually named go or loop
- 9:19Speaker 1: by convention, and instead of changing an index variable, you
- 9:22Speaker 1: just invoke the helper function again, passing the new computed
- 9:26Speaker 1: state forward as an argument.
- 9:27Speaker 2: Exactly. To iterate over an array, instead of mutating an
- 9:31Speaker 2: index from zero to one, you just call loop one,
- 9:34Speaker 2: which processes the element and then calls loop two and
- 9:37Speaker 2: so forth.
- 9:37Speaker 1: But hold on, if we use recursion for every single
- 9:41Speaker 1: loop in our entire application, aren't we going to blow
- 9:44Speaker 1: up the call stack?
- 9:45Speaker 2: Ah?
- 9:46Speaker 1: Yes, Like anyone who has written a recursive function that
- 9:48Speaker 1: goes too deep knows about the dreaded stack over flower error.
- 9:53Speaker 2: This raises an important question, and it's a critical mechanical
- 9:56Speaker 2: hurdle the author's address immediately. This is where the language
- 9:59Speaker 2: compile itself has to step in and do the heavy
- 10:02Speaker 2: lifting via a feature called tail call elimination.
- 10:05Speaker 1: Okay, walk me through what that actually does physically in
- 10:08Speaker 1: the memory stack.
- 10:09Speaker 2: So, when a standard recursive function calls itself, the computer
- 10:12Speaker 2: has to keep the previous functions memory frame open because
- 10:16Speaker 2: it still has work to do when the recursion finally returns.
- 10:18Speaker 1: Right, it's waiting for the answer exactly.
- 10:21Speaker 2: And that's what causes the stack overflow. But if the
- 10:23Speaker 2: recursive call is in the tail position, meaning it is
- 10:26Speaker 2: the absolute final instruction the function executes before returning of
- 10:30Speaker 2: the scaler, the compiler recognizes that the current memory frame
- 10:34Speaker 2: is no longer needed. Oh wow, Yeah, it physically drops
- 10:37Speaker 2: the old frame and reuses that same memory space for
- 10:41Speaker 2: the next recursive call.
- 10:42Speaker 1: So under the hood, the compiler is silently translating our
- 10:45Speaker 1: pure mathematical recursion into the exact same highly efficient, low
- 10:49Speaker 1: level machine code as an imperative wile loop.
- 10:52Speaker 2: Precisely, you get the safety of immutable state without paying
- 10:56Speaker 2: any performance penalty.
- 10:57Speaker 1: Okay, so tail call optimization saves us from stafflows. That
- 11:00Speaker 1: makes sense, But recursion alone only gets us so far. True,
- 11:04Speaker 1: if we're stuck writing rigid, single purpose recursive functions for
- 11:07Speaker 1: every tiny task, we haven't really gained much flexibility to
- 11:11Speaker 1: build dynamic applications without side effects. We have to figure
- 11:14Speaker 1: out a way to pass the logic itself around, which
- 11:17Speaker 1: brings us to higher order functions.
- 11:19Speaker 2: This is a massive leaping capability In functional programming. Functions
- 11:23Speaker 2: are first class.
- 11:23Speaker 1: Values, meaning they're treated just like data exactly.
- 11:27Speaker 2: That means a function is treated exactly the same as
- 11:30Speaker 2: a string or an integer. You can store a function
- 11:33Speaker 2: in a variable, you can return a function from a function,
- 11:36Speaker 2: and crucially, you can pass a function as an argument
- 11:39Speaker 2: to another function.
- 11:40Speaker 1: The book illustrates this with a function called format result. Right,
- 11:44Speaker 1: instead of hard coding one function that formats the absolute
- 11:47Speaker 1: value of a number for a user interface, and a
- 11:50Speaker 1: completely separate function that formats the factorial of a number,
- 11:54Speaker 1: you write a single generalized format result function, and you.
- 11:57Speaker 2: Pass the mathematical logic the absolute value function itself or
- 12:01Speaker 2: the factorial function as an argument directly into format results.
- 12:05Speaker 1: And you don't even have to define the function beforehand,
- 12:07Speaker 1: do you. Nope, you can pass what the book calls
- 12:09Speaker 1: anonymous functions right in the execution line. You just write
- 12:13Speaker 1: the logic like x erro x equals nine directly in
- 12:16Speaker 1: the argument list. The logic itself becomes portable data.
- 12:19Speaker 2: If we connect this to the broader goals of software engineering,
- 12:23Speaker 2: higher order functions allow us to abstract away the structural
- 12:26Speaker 2: skeleton of our programs from the specific domain details. We
- 12:30Speaker 2: stop writing boilerplate loops entirely.
- 12:32Speaker 1: Which is amazing. But if we're passing logic around, we
- 12:35Speaker 1: want it to be as widely applicable as possible. Hard
- 12:39Speaker 1: Coded data types restrict that they do. Like if I
- 12:42Speaker 1: write a highly optimized recursive function to search and array,
- 12:45Speaker 1: I don't want to rewrite it just because my data
- 12:47Speaker 1: changed from an integer to a string. We have to
- 12:49Speaker 1: let the type system do.
- 12:50Speaker 2: The work, and that leads directly into polymorphic functions or
- 12:55Speaker 2: abstracting over types.
- 12:57Speaker 1: The book walks through generalizing a function called fine. Initially,
- 13:01Speaker 1: it's strictly typed to search through an array of strings, right,
- 13:04Speaker 1: But the actual mechanical logic of searching an array starting
- 13:07Speaker 1: at index zero, checking at tendition, and moving to the
- 13:10Speaker 1: next index has absolutely nothing to do with strings.
- 13:13Speaker 2: The mechanism is identical whether you are searching strings, integers,
- 13:17Speaker 2: or complex nested user objects.
- 13:19Speaker 1: So we strip the specific type out. Instead of array string,
- 13:22Speaker 1: we declare the function to expect an ARRAYA, where A
- 13:25Speaker 1: is just a polymorphic placeholder for any conceivable type exactly,
- 13:29Speaker 1: and we pass in a higher order function that takes
- 13:31Speaker 1: an A and returns a boolean telling us if it
- 13:33Speaker 1: found a match.
- 13:34Speaker 2: And this is where the text gets into some truly
- 13:37Speaker 2: mind bending territory.
- 13:38Speaker 1: Oh yeah.
- 13:39Speaker 2: When you abstract away both the specific data types and
- 13:41Speaker 2: the specific operations, you start encountering these fascinating logic puzzles
- 13:46Speaker 2: where the compiler is so constrained that it practically rights
- 13:49Speaker 2: the application for you.
- 13:50Speaker 1: Yes, the partial one function puzzle. Let's break down the
- 13:54Speaker 1: signature careful because it is wild to think about it
- 13:56Speaker 1: really is. The signature is deaf partial one. And then
- 13:59Speaker 1: it takes types A, B, and C. It takes an
- 14:02Speaker 1: argument a of type A and a function F that
- 14:05Speaker 1: takes an A and a B and returns a C,
- 14:08Speaker 1: and it returns a function from B to C.
- 14:10Speaker 2: Okay, let's translate that out of code and into English.
- 14:12Speaker 1: Please do.
- 14:13Speaker 2: We're defining a function that operates on three entirely unknown
- 14:16Speaker 2: types A, B, and C. The function receives two arguments, first,
- 14:20Speaker 2: a value of type A. Second a function. Let's call
- 14:23Speaker 2: it F, which requires both an A and a B
- 14:25Speaker 2: to execute and produce a C, and our ultimate goal,
- 14:29Speaker 2: we must return a brand new function that takes a
- 14:31Speaker 2: B and returns a C.
- 14:32Speaker 1: So the puzzle is, how do you write the actual
- 14:36Speaker 1: execution body of this function when you have zero context
- 14:39Speaker 1: about what AB or C represent. They aren't database records,
- 14:43Speaker 1: they are complete unknowns.
- 14:45Speaker 2: What's fascinating here is that the lack of information is
- 14:48Speaker 2: your greatest asset. How So, because we only know the
- 14:51Speaker 2: generic types and absolutely nothing about the domain, the universe
- 14:54Speaker 2: of possible implementations shrinks down to a single point. There
- 14:59Speaker 2: is literally on one mathematically possible way to write the
- 15:03Speaker 2: code that the compiler will accept.
- 15:05Speaker 1: The authors use an incredibly intuitive analogy for this.
- 15:08Speaker 2: Oh the carrot one.
- 15:09Speaker 1: Yeah. They say, if I can give you a carrot
- 15:11Speaker 1: for an apple and a banana, and you already gave
- 15:13Speaker 1: me an apple, you just have to give me a
- 15:15Speaker 1: banana and I'll give you a carrot exactly.
- 15:17Speaker 2: Our required output is a function that takes a type B.
- 15:20Speaker 2: So we start by writing an anonymous function that accepts
- 15:23Speaker 2: a parameter B. Okay, Now, inside that anonymous functions execution block,
- 15:28Speaker 2: we have access to both B and the A that
- 15:31Speaker 2: was passed in earlier preserved in enclosure. What is the
- 15:34Speaker 2: only thing in the universe we can do with an
- 15:36Speaker 2: A and a B.
- 15:37Speaker 1: We pass them both into the function F that we
- 15:40Speaker 1: also received as an argument yes, and F magically produces
- 15:44Speaker 1: the C that our anonymous function is required to return.
- 15:48Speaker 1: The types dictate the implementation so strictly that you literally
- 15:52Speaker 1: cannot write a bug.
- 15:54Speaker 2: It's profoundly important for anyone building large scale applications because
- 15:58Speaker 2: these abstract palling morphic functions say absolutely nothing about a
- 16:02Speaker 2: specific domain. They don't know about coffee cups or credit
- 16:05Speaker 2: cards or user profiles. They are universally reusable.
- 16:09Speaker 1: That makes total sense.
- 16:11Speaker 2: Programming in the large becomes indistinguishable from programming in the small.
- 16:14Speaker 2: You're just snapping perfectly typed puzzle pieces together.
- 16:17Speaker 1: Okay, I am entirely sold on the logic pipeline. We've
- 16:20Speaker 1: solved stateful loops without mutation by leveraging tail recursion, and
- 16:24Speaker 1: we've solved rigid code by leveraging higher order polymorphic functions.
- 16:27Speaker 1: We have, but what about the data we feed into
- 16:30Speaker 1: this pipeline? How do we actually store and process massive
- 16:34Speaker 1: collections of information? If absolutely everything in our system is
- 16:37Speaker 1: strictly immutable.
- 16:38Speaker 2: Ah. Right, This requires a major paradigm shift in how
- 16:42Speaker 2: we structure memory. We have to abandon standard arrays and
- 16:45Speaker 2: adopt functional data structures, primarily the singly linked list, which
- 16:49Speaker 2: the authors explore in depth in chapter three.
- 16:52Speaker 1: Yeah, the text builds this functional list completely from scratch.
- 16:55Speaker 1: It utilizes just two data constructors, nil, which represents an
- 16:59Speaker 1: empty list, and cons, which stands for construct correct.
- 17:03Speaker 2: A con cell holds two things, a single piece of
- 17:06Speaker 2: data the head of the list, and a pointer referencing
- 17:09Speaker 2: the rest of the list, the tail. So a simple
- 17:11Speaker 2: list containing the numbers one, two, and three is structurally
- 17:15Speaker 2: represented as cons one pointing to cons two pointing to
- 17:18Speaker 2: cons three pointing to nil.
- 17:20Speaker 1: Now, to traverse this nested structure, we can't use standardifel
- 17:24Speaker 1: statements or list dot getthead getter methods.
- 17:27Speaker 2: No, you can.
- 17:27Speaker 1: Instead, we use pattern matching. And I want to make
- 17:30Speaker 1: sure we explain how this mechanically differs from a standard
- 17:33Speaker 1: switch statement.
- 17:33Speaker 2: Yeah, that's an important distinction. Pattern matching is essentially a
- 17:36Speaker 2: mechanism for destructuring. It doesn't just check the type of
- 17:40Speaker 2: the object. The compiler actually reaches inside the data structure,
- 17:44Speaker 2: unpacks the internal bindings and injects them directly into your
- 17:47Speaker 2: local scope.
- 17:48Speaker 1: So when you write case cons ht, you aren't just
- 17:52Speaker 1: checking if the object is a cons In that exact
- 17:55Speaker 1: same line of code, the compiler physically rips the head
- 17:59Speaker 1: value out and assigns it to a local variable H,
- 18:02Speaker 1: and rips the tail reference out and assigns it to
- 18:05Speaker 1: a variable T. It eliminates all the boilerplate getter methods
- 18:08Speaker 1: we are used to writing in object oriented code.
- 18:11Speaker 2: It makes traversing complex recursive data structures incredibly succinct.
- 18:16Speaker 1: It really does.
- 18:17Speaker 2: But this usually triggers the biggest, most persistent objection to
- 18:21Speaker 2: functional programming.
- 18:22Speaker 1: Which is the memory footprint. Because if this linked list
- 18:25Speaker 1: is strictly immutable, and I have a list of ten
- 18:27Speaker 1: thousand user records and my application just needs to propen
- 18:30Speaker 1: one single new user to the front, doesn't creating a
- 18:34Speaker 1: new list mean the compiler has to physically duplicate all
- 18:38Speaker 1: ten thousand existing records.
- 18:40Speaker 2: It sounds like it would.
- 18:41Speaker 1: Doesn't that absolutely throttle the application's memory and performance.
- 18:44Speaker 2: It is a completely logical deduction if you are thinking imperatively,
- 18:48Speaker 2: But the answer is a definitive no due to an
- 18:51Speaker 2: architectural concept called data sharing.
- 18:53Speaker 1: But if x's is immutable, how does the new list
- 18:57Speaker 1: actually point to it without risking that the garbae collector
- 19:00Speaker 1: or another thread is going to lock it up or
- 19:02Speaker 1: read it incorrectly.
- 19:04Speaker 2: Think about the mechanics of the con structure. If you
- 19:07Speaker 2: have an existing list in memory, let's call it access,
- 19:09Speaker 2: and you want to propen the number one, you do
- 19:12Speaker 2: not copy axis. Okay, You simply instantiate a single microscopic
- 19:16Speaker 2: new cons object. You set it's head to one, and
- 19:19Speaker 2: you said it's tail pointer to point directly at the
- 19:22Speaker 2: existing memory address of X.
- 19:24Speaker 1: Wait. Really, so both the old list and the new
- 19:26Speaker 1: list are silently sharing the exact same ten thousand elements
- 19:30Speaker 1: in memory.
- 19:30Speaker 2: Precisely because functional data structures are persistent and completely immutable,
- 19:35Speaker 2: they are inherently thread safe.
- 19:36Speaker 1: Oh wow, it is.
- 19:38Speaker 2: One hundred percent safe to share references to them across
- 19:40Speaker 2: your entire application. You never ever have to worry that
- 19:43Speaker 2: a background thread or a rogue function is going to
- 19:46Speaker 2: maliciously or accidentally modify x's while you are reading from it.
- 19:50Speaker 1: This completely eliminates the need for defensive copying. It does
- 19:54Speaker 1: like in standard imperative programming, developers are constantly copying a
- 19:58Speaker 1: raise before passing them into third party libraries, just to
- 20:01Speaker 1: protect their internal state from being corrupted.
- 20:03Speaker 2: Exactly, that defensive copying is what actually causes massive memory
- 20:08Speaker 2: bloat in enterprise object oriented systems.
- 20:10Speaker 1: That makes so much sense.
- 20:11Speaker 2: In functional programming, because the entire architecture is locked down
- 20:15Speaker 2: and pure. You just pass lightweight pointers around. So ironically,
- 20:19Speaker 2: in large scale systems, this functional data sharing actually decreases
- 20:23Speaker 2: memory overhead and increases efficiency.
- 20:26Speaker 1: It's a brilliant subversion of expectations. And once you have
- 20:29Speaker 1: these immutable, persistent lists, you can process them by applying
- 20:33Speaker 1: those higher order functions we talked about earlier, specifically utilizing
- 20:37Speaker 1: generalization functions like fold right and fold left. Instead of
- 20:40Speaker 1: writing a custom loop to some a list of numbers
- 20:43Speaker 1: and another custom loop to multiply them, you just fold
- 20:46Speaker 1: the data.
- 20:46Speaker 2: Structure you pass in the logic for what to do
- 20:48Speaker 2: with each item, and the fold function effectively replaces every
- 20:52Speaker 2: CON's constructor with your provided logic, collapsing the entire nested
- 20:56Speaker 2: structure down into a single computed result.
- 21:00Speaker 1: I've covered a tremendous amount of architectural ground today.
- 21:02Speaker 2: We really have. It's a dense text, but incredibly rewarding.
- 21:06Speaker 1: Let's summarize the journey a bit. We started by looking
- 21:09Speaker 1: at a simple, seemingly innocent side effect charging a credit
- 21:13Speaker 1: card in a by coffee function, and we saw mechanically
- 21:16Speaker 1: how that entanglement leads directly to code that is a
- 21:19Speaker 1: nightmare to test and impossible to reuse.
- 21:22Speaker 2: And by making the deliberate architectural choice to simply return
- 21:26Speaker 2: a data value representing the charge rather than executing the
- 21:29Speaker 2: action immediately, we unlocked a completely pure core.
- 21:33Speaker 1: We saw how referential transparency guarantees that our expressions act
- 21:37Speaker 1: like architectural pipelines completely isolated from the outside world.
- 21:41Speaker 2: Yep. We learned how leveraging tail call elimination allows us
- 21:45Speaker 2: to write elegant recursive loops without blowing up the memory stack,
- 21:50Speaker 2: and how higher order polymorphic functions allow the compiler to
- 21:54Speaker 2: literally solve logic puzzles for us based strictly on type constraints.
- 21:59Speaker 1: And finally, we saw how functional data structures use pattern
- 22:02Speaker 1: matching to destructure data elegantly, and how data sharing eliminates
- 22:06Speaker 1: memory blut and thread safety issues without ever mutating a
- 22:10Speaker 1: single variable. It all ties together, It does that terrifying
- 22:13Speaker 1: fragile house of cards codebase we talked about at the beginning,
- 22:16Speaker 1: functional programming replaces it with interlocking, sterile, highly predictable pipelines.
- 22:22Speaker 2: And for you listening, it's worth taking a step back
- 22:24Speaker 2: and realizing that many of the modern best practices you
- 22:27Speaker 2: probably already use, like writing single responsibility functions, utilizing dependency injection,
- 22:33Speaker 2: or explicitly declaring variables as immutable constants, are fundamentally just
- 22:37Speaker 2: fragments of functional programming.
- 22:39Speaker 1: That's a really good point.
- 22:40Speaker 2: What this text does is take those intuitive best practices
- 22:44Speaker 2: to their absolute, rigorous, logical endpoint. It provides a mathematical
- 22:49Speaker 2: shortcut to writing highly modular code that is incredibly resistant
- 22:54Speaker 2: to bugs.
- 22:55Speaker 1: It is undeniably a steep learning curve to completely rewire
- 22:58Speaker 1: how you think about stay. But the view from the
- 23:01Speaker 1: top of that curve is crystal clear architecture. But before
- 23:06Speaker 1: we sign off, I want to leave you with a
- 23:07Speaker 1: final provocative thought. Ooh, okay, it's a puzzle hinted at
- 23:11Speaker 1: near the very end of our source text.
- 23:12Speaker 2: Today, ah, the issue with exceptions exactly.
- 23:15Speaker 1: The authors briefly mentioned that standard exceptions like throwing a
- 23:18Speaker 1: runtime error when an application encounters a problem should actually
- 23:22Speaker 1: only be used for fatal, unrecoverable system crashes, never for
- 23:26Speaker 1: routine control.
- 23:27Speaker 2: Flow, because if you analyze it mechanically, throwing an exception
- 23:31Speaker 2: is the ultimate side effect.
- 23:32Speaker 1: Wait, really it's a side effect.
- 23:34Speaker 2: Yes, it completely breaks referential transparency. If a function throws
- 23:37Speaker 2: an exception, you cannot cleanly substitute it with a return value.
- 23:40Speaker 2: Oh I say, it behaves exactly like a rogue go
- 23:43Speaker 2: to statement. It abruptly halts the execution pipeline and rips
- 23:48Speaker 2: the context out to some hidden, unpredictable catch block miles
- 23:51Speaker 2: away in the call stack.
- 23:53Speaker 1: That is wild. So here's the puzzle for you to ponder.
- 23:56Speaker 1: If throwing an error acts as a go to statement,
- 23:58Speaker 1: that breaks the absolute fundamental rule of pure functions. How
- 24:03Speaker 1: do pure functional programmers handle routine daily.
- 24:06Speaker 2: Errors that it's a great question.
- 24:08Speaker 1: Like if a user inputs invalid data, or a database
- 24:11Speaker 1: connection temporarily drops, or a file goes missing, how do
- 24:15Speaker 1: you handle those failures without ever throwing exception?
- 24:18Speaker 2: It forces you to completely rethink what an error actually
- 24:21Speaker 2: is in the context of your application domain.
- 24:23Speaker 1: So the next time you find yourself writing a standard
- 24:25Speaker 1: trycatch block, challenge yourself to mull that over. How could
- 24:28Speaker 1: you represent that application crash as a pure mathematical data value,
- 24:32Speaker 1: exactly like we did with the coffee shop credit card receipt.
- 24:35Speaker 1: Think about it and we will catch you on the
- 24:36Speaker 1: next deep dive.