Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Real-World Functional Programming

Real-World Functional Programming

With Examples in F# and C#
Make .NET code safer and easier to scale by borrowing functional techniques, without abandoning C#.
by Tomas Petricek 2009 560 pages
3.92
180 ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Use functional ideas inside .NET to make real programs clearer, safer, and scalable

Describe the result. Functional programming shifts attention from a sequence of commands to a description of the desired result. Instead of looping through customers and deciding what to display, a program can say to show every customer who meets a condition. LINQ queries and declarative user-interface descriptions such as XAML already use this approach in mainstream .NET development. F# makes it easier to extend the same idea by building small libraries that express the concepts of a particular problem.

A practical paradigm. The book presents F# as a multi-paradigm .NET language, not a demand to abandon object-oriented design or existing libraries. Its examples include drawing charts, processing documents, downloading web data, and creating animations. C# developers can use many of the same ideas through lambdas, delegates, LINQ, and immutable types.

Analysis

What's distinctive is the book's insistence that functional programming earns its place through practical leverage, not aesthetic purity. Declarative code creates a useful separation between intent and execution, much like a database query leaves optimization to a query planner. That separation improves readability and can enable parallel execution. It also has limits: a concise query can conceal expensive work or surprising evaluation behavior. The strongest practice is therefore not to prefer declarative syntax everywhere, but to use it where the intent is stable and make performance-sensitive boundaries observable.

Replace hidden mutation with values you can trace, test, and safely share

Make changes explicit. An immutable value cannot be altered after creation. An operation that appears to change a rectangle instead returns a new rectangle, making the result visible in the code. This helps explain behavior: a method call cannot quietly modify unrelated objects through shared state. F# uses immutable values and data structures by default, while C# can use read-only fields, immutable classes, or functional collection types.

Dependencies become visible. If two calculations use immutable inputs and return values, changing their execution order cannot secretly change their meaning. In a game example, updating a monster and checking whether a player is near the updated monster must occur in order, while independently updating a player and monster can run concurrently. The same clarity makes unit tests simpler: verify outputs for inputs instead of auditing hidden side effects.

Analysis

Immutability is best understood as control over aliasing, the situation in which multiple parts of a program can reach the same mutable object. Removing that shared write access reduces a major source of concurrency bugs and makes local reasoning more reliable. It does not make a whole application pure: file access, user interfaces, and .NET objects can still have side effects. The useful engineering move is to contain mutation at clear boundaries, then pass immutable results between components. That keeps the safety benefit without pretending real software has no state.

Design the data first, then choose the right representation for each task

Model the domain directly. F# tuples group a known number of values, records give those values names, and discriminated unions represent a closed set of alternatives. Pattern matching lets code handle each alternative explicitly, while the compiler can warn when a case is missing. The option type represents a value that may be absent, so callers must handle both the present and missing cases rather than accidentally dereferencing null.

One model need not do everything. The document application used a flat list of positioned elements for drawing, a recursive hierarchy for editing and composing parts, and XML for storage. Functions translated between these representations. In C#, related structures can be expressed with classes and design patterns such as Composite, Decorator, and Visitor, though the functional representation makes alternatives and recursive structure more direct.

Analysis

Choosing a data representation is a form of deciding which operations should be easy. A flat list makes iteration and drawing straightforward; a recursive tree makes nesting and editing natural. This is closely related to database normalization and compiler intermediate representations, where different forms serve different stages of a pipeline. Multiple representations do introduce conversion code and the possibility of disagreement. The design works best when each representation has a clear purpose and transformations are explicit, testable functions rather than scattered field-by-field rewrites.

Turn repeated behavior into functions, then compose a language around the problem

Pass behavior as data. A higher-order function accepts another function as an argument or returns one. This lets a reusable operation handle the repeated structure while a supplied function specifies what varies. Filtering a list, applying a color filter, and testing loan applicants all follow this pattern. Lambda functions make small behaviors easy to pass inline; partial application and function composition build larger behaviors from smaller ones.

Make the domain readable. The book uses these ideas to create domain-specific libraries, including a language for describing animations from moving objects and composable drawings. C# can approximate the style with delegates, extension methods, and fluent interfaces. F# also supports computation expressions, which let a library define special behavior for familiar-looking code blocks.

Analysis

The important shift is from writing one-off procedures to designing a small vocabulary that makes a family of tasks legible. This resembles algebra: once operations have clear laws, larger expressions can be composed and reasoned about systematically. A domain-specific language can also reduce training costs when its primitives match the team's actual concepts. The risk is abstraction without a stable domain. If the vocabulary hides evaluation order, costs, or failure modes, the apparent clarity becomes a debugging tax. Good DSLs expose a small set of meaningful operations and preserve escape hatches to ordinary code.

Prototype interactively, then harden the F# code for teams and .NET consumers

Test ideas immediately. F# Interactive lets developers enter a function, try sample inputs, inspect inferred types, and revise the code without building a full application. The book uses this iterative process to explore .NET libraries, parse data, and test calculations before packaging them. Early experiments can later become repeatable unit tests, with immutable values and structural equality making expected results easier to compare.

Add structure when it matters. Once the approach works, F# code can be organized into modules, members, interfaces, and classes. Object expressions implement interfaces without a named class, while type extensions can add members to an existing F# type. Public F# records and members appear as ordinary .NET types to C#, and delegates can provide C#-friendly entry points for higher-order functions.

Analysis

Interactive development turns the compiler into a partner in exploration: type inference provides feedback while a design is still cheap to change. This is valuable for unfamiliar APIs and uncertain data, where formal architecture too early can encode the wrong assumptions. The transition to documented classes and interfaces is equally important because experiments are not automatically good library contracts. A useful distinction is between exploratory convenience and public stability. Keeping that distinction visible helps teams benefit from rapid prototyping without exporting every temporary choice as permanent API.

Keep recursion safe, collections efficient, and expensive results reusable

Recursion needs engineering. A recursive list sum can overflow the stack on a sufficiently large input because work remains after each recursive call. Tail recursion avoids this when the recursive call is the final operation, often by carrying an accumulator. When a tree traversal needs several recursive results, continuations can carry the remaining work explicitly. The book also shows memoization, which caches a function's result so repeated calls with the same input need not recompute it.

Choose structures deliberately. Functional lists make adding to the front efficient, but adding to the end requires rebuilding the list. Arrays support fast indexed access and can be processed functionally by constructing a new result, even if the implementation uses local mutation. Lazy values compute only when needed and cache the result, as in the photo browser that resizes each image only when selected.

Analysis

These techniques expose a productive tension in functional programming: the clearest recursive definition is not always the safest or fastest implementation. Tail calls, accumulators, memoization, arrays, and continuations are not aesthetic preferences; they respond to concrete costs in stack space, allocation, or repeated computation. Memoization is especially conditional, since it trades memory for time and only helps when reuse is likely. The best sequence is to preserve a simple specification, measure realistic workloads, and optimize the bottleneck without obscuring the underlying algorithm.

Let sequences and computations control when work runs, not just what it returns

Sequences defer work. A sequence represents ordered values that may be generated only as needed. F# sequence expressions use yield to produce an element and yield! to incorporate another sequence. C# iterators provide similar deferred generation with yield return. Sequences can be infinite, which is useful when a consumer needs only a finite portion, such as generating colors on demand for a chart.

Computation expressions customize execution. F# uses the same general mechanism for asynchronous workflows, option values, and logging. In an asynchronous workflow, let! waits for an operation without occupying a thread, while return! composes another workflow. The book applies this to World Bank XML data, converts values into typed records and units of measure, and sends results to Excel for analysis and charting.

Analysis

Deferred computation separates the description of a pipeline from the moment its values are demanded, a principle shared by iterators, database cursors, and streaming systems. This can save work and support unbounded data sources, but laziness also moves failures and costs to the point of consumption. Computation expressions are more ambitious: they let a library alter how familiar code composes, as with asynchronous operations or missing values. That flexibility is powerful when the execution model is coherent, but users need clear rules about blocking, exceptions, and when side effects occur.

Parallelize independent work by changing the execution strategy, not the algorithm

Use declarative parallelism. When processing independent collection elements, PLINQ can replace sequential LINQ operators with parallel ones. The book demonstrates this with prime counting: filtering a large range can run across multiple cores, and its example on a dual-core machine reports roughly 180% to 185% of sequential speed. F# provides corresponding functions and parallel sequence expressions.

Split independent tasks safely. Immutable inputs make it easier to identify work that can run concurrently. The simulation example computes new animal and predator locations from a fixed state, then constructs a new state. For local array processing, Parallel.For can parallelize a loop when iterations write to separate output locations. Shared mutable objects still require care, as with a Random generator protected by a lock.

Analysis

The book's central concurrency insight is that independence is easier to establish when computation is expressed as value-in, value-out transformations. This resembles the dataflow model used in parallel systems: nodes exchange results rather than coordinating shared writes. Yet parallelism is not free. Scheduling overhead, uneven workloads, memory bandwidth, and synchronization can erase theoretical gains, as the chapter's need to avoid creating too many tasks illustrates. The practical rule is to parallelize coarse, demonstrably independent work and measure it on representative data, rather than treating every loop as a candidate.

Model event-driven systems as workflows and messages instead of tangled callbacks

Compose event streams. F# events can be treated as values and transformed with operations such as filter, map, merge, and scan. The book's click counter merges increment and decrement events, then accumulates their values. This makes the behavior visible as a pipeline rather than burying conditions inside several callbacks. C# can use a similar style through the Reactive LINQ library and query syntax.

Represent interaction as process state. Asynchronous workflows can wait for events while keeping control flow explicit, as in the rectangle-drawing example with waiting and drawing states. For shared application state, a mailbox processor handles messages sequentially, including updates and requests for the current state. This message-passing pattern can also coordinate concurrent tasks without exposing shared mutable state to every caller.

Analysis

Reactive design is not merely a different syntax for callbacks. It changes the unit of reasoning from individual handlers to flows of events, states, and messages. This is valuable because temporal behavior becomes inspectable: a click stream can be filtered, accumulated, and rendered as one composition. The same model appears in actor systems and event-sourced architectures. Its costs deserve equal attention: event ordering, cancellation, backpressure, and error propagation can become subtle. A small, explicit state machine and narrowly defined message types keep the abstraction understandable as interactions multiply.

Analysis

The book's unifying claim is that functional programming is a practical design discipline for .NET, not a niche preference for mathematical elegance. Its progression is deliberate: start with values and functions, use them to model data and behavior, then add object-oriented structure where libraries and teams require it. This sequence explains why F# examples often begin as compact interactive experiments and end as classes, interfaces, or reusable components.

Three mechanisms carry most of the argument. Immutability makes dependencies visible, which improves testing and provides a basis for safe parallelism. Higher-order functions turn recurring control patterns into reusable operations, making code more declarative. Computation expressions and sequence abstractions let libraries shape evaluation itself, supporting laziness, asynchronous work, logging, and event processing without changing the underlying .NET platform.

The examples give these ideas practical texture: XML documents become typed data, World Bank indicators become unit-aware values and Excel charts, image filters move from local mutation to parallel arrays, and a simulation computes a new world state from an old one. The book also avoids a false opposition between functional and object-oriented design. F# records and discriminated unions suit internal models, while members, interfaces, and classes make mature APIs easier to share with C#.

The main qualification is that functional structure does not eliminate operational complexity. Lazy evaluation shifts when work happens, parallel execution introduces scheduling costs, and real applications still interact with mutable APIs, files, networks, and user interfaces. The strongest lesson is therefore architectural: keep state and effects at explicit boundaries, model the core transformations as values, and use measurement to decide where advanced techniques pay off. That approach makes functional programming useful even when an entire application cannot, or should not, be purely functional.

Summary in 30 Seconds
Immutable data makes dependencies easier to trace, test, and run concurrently. Higher-order functions capture recurring patterns so small operations can be combined into domain-specific tools. Lazy sequences and asynchronous workflows defer work until needed, while event streams and message processing keep interaction logic explicit. Parallel processing can speed independent tasks, with one example reaching roughly 180% to 185% of sequential performance on a dual-core machine. Choose data structures and execution strategies to fit the work.
Contains spoilers

Last updated:

Report Issue

Review Summary

3.92 out of 5
Average of 180 ratings from Goodreads and Amazon.

Real-World Functional Programming received mixed reviews, with an average rating of 3.92/5. Readers appreciated its introduction to functional programming concepts, especially for C# developers learning F#. The book's side-by-side C# and F# examples were praised for illustrating differences between imperative and functional approaches. Some found it comprehensive and helpful for understanding F# syntax and functional programming principles. However, critics felt it was too long, with unnecessary C# examples and UI-focused content. Several reviewers noted it might be more suitable for beginners in functional programming rather than those seeking advanced concepts.

Your rating:
4.4
62 ratings
Want to read the full book?

Glossary

Discriminated union

A value with named alternatives

An F# type whose values can take one of several declared forms, called cases or discriminators. Each case can carry values of its own. Pattern matching examines the case and extracts its contents, and the compiler can warn when a match does not cover every possibility. It is useful for representing alternatives such as shapes, options, and recursive trees.

Higher-order function

A function that handles functions

A function that accepts another function as an argument, returns a function, or does both. It allows common structure to be written once while a supplied function specifies the part that varies. Examples include mapping a function over a collection, filtering with a predicate, and composing functions into a larger operation.

Tail recursion

Recursion with no remaining work

A recursive call is tail-recursive when the function returns its result immediately, without doing additional work after the call completes. F# can optimize such calls so they do not require an ever-growing stack. An accumulator often turns a calculation that needs post-call work into a tail-recursive one.

Continuation

A description of what runs next

A function passed to a computation to specify what should happen after that computation produces a result. Continuations can represent work that would otherwise occur after a recursive call, allowing some tree traversals to become tail-recursive. Asynchronous workflows also use continuations to resume code when an operation completes.

Sequence expression

A block that generates a sequence

An F# construct introduced with seq that produces values using yield and can include other sequences using yield!. Its code runs lazily as a consumer requests elements, so it can represent large or infinite sequences. Sequence expressions can contain loops, conditions, and recursion, and parallel variants can change how elements are processed.

Computation expression

A customizable execution block

An F# syntax for writing a block of code whose behavior is defined by a computation builder. The builder supplies operations such as Bind and Return, which determine how values are combined and what special execution rules apply. The book uses computation expressions for sequences, asynchronous workflows, option values, and logging.

Asynchronous workflow

Nonblocking computation with continuations

An F# computation, represented by the Async type, that can perform operations without keeping a thread blocked while waiting. The async computation builder supports constructs such as let! and return!, which compose asynchronous steps. The library can run workflows in the background, combine them in parallel, or wait for their results.

MailboxProcessor

A message-driven state process

An F# component that receives messages through a queue and processes them sequentially. Its internal state can be passed from one iteration of its processing loop to the next. Other parts of the program communicate with it by posting messages, optionally receiving replies, rather than directly sharing and modifying its state.

Units of measure

Units checked as part of types

An F# feature that attaches units such as kilometers, hours, or percentages to numeric values. The compiler tracks these units through calculations and rejects incompatible operations, such as comparing speeds expressed in different units without conversion. Units can also be combined algebraically, helping catch mistakes in calculations before execution.

Memoization

Caching results of function calls

A technique that stores the result of a function call and reuses it when the same input occurs again. It is most suitable for functions whose results depend only on their inputs. Memoization can reduce repeated computation, as in the book's factorial example, but it uses memory and may provide little benefit when inputs rarely repeat.

Language oriented programming

A vocabulary tailored to a domain

A design approach that creates libraries or small languages for expressing problems in a particular area. The book demonstrates internal languages built from F# functions and types, C# extension methods and fluent interfaces, and computation expressions. The aim is to let users describe intent with domain-specific operations instead of repeatedly exposing implementation details.

About the Author

Tomas Petricek is the author of Real-World Functional Programming. He is known for his expertise in functional programming, particularly in F# and its applications in the .NET ecosystem. Petricek has contributed significantly to the field of programming language theory and practice, focusing on making functional programming concepts accessible to developers from object-oriented backgrounds. His work often emphasizes practical applications of functional programming in real-world scenarios, bridging the gap between theoretical concepts and industry implementation. Petricek is recognized for his ability to explain complex programming concepts in a clear and understandable manner, making him a respected figure in the functional programming community.

Download PDF

To save this Real-World Functional Programming summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.33 MB     Pages: 16

Download EPUB

To read this Real-World Functional Programming summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.40 MB     Pages: 20
Want to read the full book?
Follow
Listen
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...