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

Learning Functional Data Structures and Algorithms

Book Description

Learn functional data structures and algorithms for your applications and bring their benefits to your work now

About This Book

  • Moving from object-oriented programming to functional programming? This book will help you get started with functional programming.
  • Easy-to-understand explanations of practical topics will help you get started with functional data structures.
  • Illustrative diagrams to explain the algorithms in detail.
  • Get hands-on practice of Scala to get the most out of functional programming.

Who This Book Is For

This book is for those who have some experience in functional programming languages. The data structures in this book are primarily written in Scala, however implementing the algorithms in other functional languages should be straight forward.

What You Will Learn

  • Learn to think in the functional paradigm
  • Understand common data structures and the associated algorithms, as well as the context in which they are commonly used
  • Take a look at the runtime and space complexities with the O notation
  • See how ADTs are implemented in a functional setting
  • Explore the basic theme of immutability and persistent data structures
  • Find out how the internal algorithms are redesigned to exploit structural sharing, so that the persistent data structures perform well, avoiding needless copying.
  • Get to know functional features like lazy evaluation and recursion used to implement efficient algorithms
  • Gain Scala best practices and idioms

In Detail

Functional data structures have the power to improve the codebase of an application and improve efficiency. With the advent of functional programming and with powerful functional languages such as Scala, Clojure and Elixir becoming part of important enterprise applications, functional data structures have gained an important place in the developer toolkit. Immutability is a cornerstone of functional programming. Immutable and persistent data structures are thread safe by definition and hence very appealing for writing robust concurrent programs.

How do we express traditional algorithms in functional setting? Won't we end up copying too much? Do we trade performance for versioned data structures?

This book attempts to answer these questions by looking at functional implementations of traditional algorithms.

It begins with a refresher and consolidation of what functional programming is all about. Next, you'll get to know about Lists, the work horse data type for most functional languages. We show what structural sharing means and how it helps to make immutable data structures efficient and practical.

Scala is the primary implementation languages for most of the examples. At times, we also present Clojure snippets to illustrate the underlying fundamental theme. While writing code, we use ADTs (abstract data types). Stacks, Queues, Trees and Graphs are all familiar ADTs. You will see how these ADTs are implemented in a functional setting. We look at implementation techniques like amortization and lazy evaluation to ensure efficiency.

By the end of the book, you will be able to write efficient functional data structures and algorithms for your applications.

Style and approach

Step-by-step topics will help you get started with functional programming. Learn by doing with hands-on code snippets that give you practical experience of the subject.

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. Learning Functional Data Structures and Algorithms
    1. Learning Functional Data Structures and Algorithms
    2. Credits
    3. About the Authors
    4. About the Reviewer
    5. www.PacktPub.com
      1. Why subscribe?
    6. Customer Feedback
    7. 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. Downloading the color images of this book
        3. Errata
        4. Piracy
        5. Questions
    8. 1. Why Functional Programming?
      1. The imperative way
      2. Higher level of abstraction
      3. Functional programming is declarative
      4. No boilerplate
      5. Higher order functions
        1. Eschewing null checks
      6. Controlling state changes
      7. Recursion aids immutability
      8. Copy-on-write
      9. Laziness and deferred execution
      10. Composing functions
      11. Summary
    9. 2. Building Blocks
      1. The Big O notation
      2. Space/time trade-off
        1. A word frequency counter
        2. Matching string subsets
      3. Referential transparency
      4. Vectors versus lists
        1. Updating an element
        2. Not enough nodes
      5. Complexities and collections
        1. The sliding window
        2. Maps
        3. Persistent stacks
        4. Persistent FIFO queues
        5. Sets
        6. Sorted set
      6. Summary
    10. 3. Lists
      1. First steps
      2. List head and tail
      3. Drop elements
      4. Concatenating lists
      5. Persistent data structures
      6. Tail call optimization
      7. List append
      8. List prepend
      9. Getting value at index
      10. Modifying a list value
      11. Summary
    11. 4. Binary Trees
      1. Node definitions
      2. Building the tree
        1. Size and depth
        2. Complete binary trees
      3. Comparing trees
        1. Flipping a binary tree
        2. Binary tree traversal
      4. The accumulator idiom
      5. Binary Search Trees
        1. Node insertion
        2. Searching a key
        3. Updating a value
      6. Exercising it
      7. Summary
    12. 5. More List Algorithms
      1. Binary numbers
        1. Addition
        2. Multiplication
      2. Greedy algorithms and backtracking
        1. An example of a greedy algorithm
        2. The backtracking jig
      3. Summary
    13. 6. Graph Algorithms
      1. Reversing a list
      2. Graph algorithms
        1. Graph traversal
        2. Avoiding list appending
        3. Topological sorting
      3. Cycle detection
        1. Printing the cycle
      4. Summary
    14. 7. Random Access Lists
      1. Incrementing a binary number
        1. Adding two binary numbers
      2. List of tree roots
        1. Insertion
        2. Lookup
        3. Removal, head, and tail
        4. Update
      3. Summary
    15. 8. Queues
      1. Understanding FIFO queues
      2. Functional FIFO queues
      3. Invariants
      4. Implementing a priority queue
      5. Understanding priority queues/heaps
      6. Leftist trees
      7. Functional heaps
      8. Summary
    16. 9. Streams, Laziness, and Algorithms
      1. Program evaluation
        1. Eager evaluation
      2. Argument evaluation
        1. Lazy evaluation
          1. Lazy evaluation in Scala
          2. Lazy evaluation in Clojure
      3. Memoization - remembering past results
        1. Memoization in Scala
        2. Memoization in Clojure
          1. Memoizing simpleFactFun
      4. Streams
        1. Stream in Scala
        2. Indexing the elements of a stream
        3. Creation of an infinite length stream
          1. Stream is immutable
          2. Creating a stream from another
        4. Stream to list
          1. Appending one stream to another
          2. Length of a stream
        5. Some mathematical functions of the stream class
        6. Some more methods of the stream class
        7. Streams (lazy sequence) in Clojure
          1. Creating a memoized function of lazy sequences in Clojure
      5. Some algorithms on stream
        1. Arithmetic progression
          1. Arithmetic progression in Scala
          2. Arithmetic progression in Clojure
        2. Standard Brownian motion
          1. Standard Brownian motion in Scala
          2. Standard Brownian motion in Clojure
        3. Fibonacci series
          1. First form of Fibonacci series
          2. Second form of Fibonacci series
          3. Fibonacci series in Scala
          4. Fibonacci series in Clojure
      6. Summary
    17. 10. Being Lazy - Queues and Deques
      1. Imperative implementations
      2. Amortization
      3. Problem with queues
      4. Strict versus lazy
      5. Streams
      6. Streams meet queues
      7. A sense of balance
      8. Amortized deques
      9. Summary
    18. 11. Red-Black Trees
      1. Terminology
      2. Almost balanced trees
      3. The concept of rotation
      4. Red-Black trees
      5. Inserting a node
        1. The Black-Red-Red path
        2. Left, left - red child and grand child
        3. Left child, right grand child
        4. Right child, right grand child
        5. Right, left
      6. Verifying the transformation
      7. Complexity
      8. Summary
    19. 12. Binomial Heaps
      1. Binomial trees
        1. Left child, right sibling
      2. A binomial heap
        1. Linking up
        2. Inserting a value
      3. Binary number equivalence
        1. Merging
        2. Find the minimum
        3. Deleting the minimum
        4. Exercising the code
        5. Complexity
      4. Summary
    20. 13. Sorting
      1. Stable and unstable sorting
        1. Stable sorting
        2. Unstable sorting
      2. Bubble sort
        1. Scala implementation of bubble sort
        2. Complexity of bubble sort
      3. Selection sort
        1. Complexity of selection sort
      4. Insertion sort
        1. Complexity of insertion sort
      5. Merge sort
        1. Splitting the sequence
        2. Merging two sorted subsequences
        3. Complexity of merge sort
      6. Quick sort
        1. Partition
        2. Complexity of quick sort
      7. Summary