O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Scala Functional Programming Patterns

Book Description

Grok and perform effective functional programming in Scala

About This Book

  • Understand functional programming patterns by comparing them with the traditional object-oriented design patterns
  • Write robust, safer, and better code using the declarative programming paradigm
  • An illustrative guide for programmers to create functional programming patterns with Scala

Who This Book Is For

If you have done Java programming before and have a basic knowledge of Scala and its syntax, then this book is an ideal choice to help you to understand the context, the traditional design pattern applicable, and the Scala way. Having previous knowledge of design patterns will help, though it is not strictly necessary.

What You Will Learn

  • Get to know about functional programming and the value Scala's FP idioms bring to the table
  • Solve day-to-day programming problems using functional programming idioms
  • Cut down the boiler-plate and express patterns simply and elegantly using Scala's concise syntax
  • Tame system complexity by reducing the moving parts
  • Write easier to reason about concurrent code using the actor paradigm and the Akka library
  • Apply recursive thinking and understand how to create solutions without mutation
  • Reuse existing code to compose new behavior
  • Combine the object-oriented and functional programming approaches for effective programming using Scala

In Detail

Scala is used to construct elegant class hierarchies for maximum code reuse and extensibility and to implement their behavior using higher-order functions. Its functional programming (FP) features are a boon to help you design “easy to reason about” systems to control the growing software complexities. Knowing how and where to apply the many Scala techniques is challenging. Looking at Scala best practices in the context of what you already know helps you grasp these concepts quickly, and helps you see where and why to use them.

This book begins with the rationale behind patterns to help you understand where and why each pattern is applied. You will discover what tail recursion brings to your table and will get an understanding of how to create solutions without mutations. We then explain the concept of memorization and infinite sequences for on-demand computation. Further, the book takes you through Scala’s stackable traits and dependency injection, a popular technique to produce loosely-coupled software systems.

You will also explore how to currying favors to your code and how to simplify it by de-construction via pattern matching. We also show you how to do pipeline transformations using higher order functions such as the pipes and filters pattern. Then we guide you through the increasing importance of concurrent programming and the pitfalls of traditional code concurrency. Lastly, the book takes a paradigm shift to show you the different techniques that functional programming brings to your plate.

This book is an invaluable source to help you understand and perform functional programming and solve common programming problems using Scala’s programming patterns.

Style and approach

This is a hands-on guide to Scala's game-changing features for programming.

It is filled with many code examples and figures that illustrate various Scala idioms and best practices.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Scala Functional Programming Patterns
    1. Table of Contents
    2. Scala Functional Programming Patterns
    3. Credits
    4. About the Author
    5. Aknowledgement
    6. About the Reviewers
    7. www.PacktPub.com
      1. Support files, eBooks, discount offers, and more
        1. Why subscribe?
        2. Free access for Packt account holders
    8. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    9. 1. Grokking the Functional Way
      1. Abstractions
      2. Concise expression
      3. Functions
      4. Immutable
      5. Referential transparency
      6. The problem – grouping continuous integers
        1. Java code
        2. Going scalaish
        3. Thinking recursively...
        4. Reusability – the commonality/variability analysis
        5. The one-liner shockers
      7. Scala idioms
      8. Patterns and those aha! moments
        1. The command design pattern
        2. The strategy design pattern
          1. Passing algorithms around
      9. Summary
    10. 2. Singletons, Factories, and Builders
      1. Singletons – being one and only one
      2. Null Objects – singletons in another garb
        1. Null Objects – the Scala way
        2. Options are container
      3. Scala singletons
        1. The apply() factory method
        2. The factory method pattern
        3. The Scala version
      4. Builders
        1. Ease of object creation
        2. Scala shines again
      5. Summary
    11. 3. Recursion and Chasing your Own Tail
      1. Recursive structures
      2. Pattern matching
        1. Deconstruction with case statements
        2. Stack overflows
      3. Tail recursion to the rescue
      4. Getting the nth element of a list
      5. An expression parser
      6. Persistent data structures
      7. Two forms of recursion
      8. Summary
    12. 4. Lazy Sequences – Being Lazy, Being Good
      1. Illusion and reality – the proxy pattern
      2. Hibernate's lazy loading
      3. Lazy val – calling by need
      4. Infinite sequences – Scala streams
      5. Recursive streams
      6. Memoization and the flyweight pattern
      7. Call by name
      8. Streams are collections
      9. Sieve of Eratosthenes
      10. A view to a collection
      11. Summary
    13. 5. Taming Multiple Inheritance with Traits
      1. The iterator design pattern
      2. Interfaces as types
      3. The dreaded diamond
      4. Traits – Scala's rich interfaces
      5. Mix-ins – rich interfaces
      6. Frills and thrills – the decorator pattern
      7. Scala's easy and breezy decorations – stackable modifications
      8. Dependencies injection pattern
      9. A taste of the cake pattern
      10. Sealed traits
      11. Defeating the dreaded diamond
      12. Summary
    14. 6. Currying Favors with Your Code
      1. Functions as first-class values
      2. Roping in a scope
      3. Local functions – hiding and biding their time
      4. The underscore – Scala's Swiss army knife
      5. A taste of the curry
        1. Type inference
        2. Of implicits and explicits
        3. Stylish blocks
      6. The loan pattern
      7. Serving the curry
      8. Frills and thrills – decorators again
      9. Wrapping it up
      10. Summary
    15. 7. Of Visitors and Chains of Responsibilities
      1. A tale of two hierarchies
      2. The Visitor pattern
        1. Many hues of pattern matching
          1. De-structuring
          2. Typed patterns
          3. Pattern guards
          4. Tuple explosion
      3. Partial functions
        1. Visitor pattern – the Scala way
        2. Lifting it up
      4. The chain of responsibility
        1. Scalaish Chain Of Responsibilities
        2. Match and mismatch – the collect idiom
      5. Summary
    16. 8. Traversals – Mapping/Filtering/Folding/Reducing
      1. Iterating the Scala way
      2. A validation problem
        1. Setting the stage
          1. First cut–using arrays
          2. Second cut–using a map
          3. Third cut–using a for expression
          4. Fourth cut–using foldLeft
          5. Fifth cut–using andThen
          6. Sixth cut–using compose
      3. Foreach–sugary sweetener
        1. One generator
        2. A generator and a filter
        3. Two generators
      4. Monads
      5. Reduce
      6. Summary
    17. 9. Higher Order Functions
      1. The strategy design pattern
      2. A strategy in Scala land
      3. Functors
        1. Maps
      4. Monads
      5. FlatMap
      6. Monoids
      7. An inverted index
      8. Pipes and filters
      9. Pipes and filters – the Scala version
      10. It is a Monoid
      11. Lazy collections
      12. Summary
    18. 10. Actors and Message Passing
      1. The recursive grep
      2. The producer/consumer pattern
      3. Threads – masters and slaves
      4. Events
      5. Immutability is golden
      6. Akka actors take the stage
      7. Summary
    19. 11. It's a Paradigm Shift
      1. Verbosity
      2. Sorting it out!
        1. Sorted
        2. SortBy
        3. SortWith
        4. Scalaish Schwartzian transform
      3. Functional error handling
        1. Pattern matching
      4. Threads and futures
        1. Scala's Futures
      5. Parser combinators
      6. Summary
    20. Index