A functional programming pattern is a recurring way to structure code around abstraction, mathematical properties, immutable transformations, and controlled effects. Functional idioms express what domain data is and how its properties constrain operations; design patterns more often describe external mechanisms for coordinating a system. section 1.5 section 1.5.3
These patterns address problems that become difficult when state and side effects are handled imperatively. Purity, immutability, and safe effect representations can reduce accidental complexity in parallel and distributed programming. section 1.5
Common functional patterns and idioms include:
- LINQ, Java streams, and C++ ranges structure data processing through functional techniques. section 1.5.3
- Monads organize computations involving input-output, changing state, and other effects while separating data from computation. section 1.5.4
- Functional software transactional memory manages concurrent state through a small conceptual vocabulary rather than raw threads and manual synchronization. section 1.5.3
- Declarative embedded domain-specific languages express task-specific operations in a compact, expressive form. section 1.5.3
Composing fallible lookups
A lookup may return a Maybe value, so retrieving a user, extracting a name, and taking its first character creates nested case analysis. Monadic composition expresses the same sequence through the values' mathematical meaning and propagates failure without repeating the branching structure. section 1.5.4
getUserInitials :: Int -> Maybe Char
getUserInitials key =
case getUser key users of #1
Nothing -> Nothing
Just user -> case getUserName user of #2
Nothing -> Nothing
Just name -> Just (head name)
Inspect the explicit nested case analysis for getUserInitials, where each Maybe result requires another success-or-failure branch. section 1.5.4
getUserInitials' :: Int -> Maybe Char getUserInitials' key = do user <- getUser key users #1 name <- getUserName user #2 Just (head name)
Compare the monadic version, which sequences the same lookups while preserving the Maybe result and its failure behavior. section 1.5.4
