Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Scala Functional Programming Patterns

You're reading from   Scala Functional Programming Patterns Grok and perform effective functional programming in Scala

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher
ISBN-13 9781783985845
Length 298 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Atul S. Khot Atul S. Khot
Author Profile Icon Atul S. Khot
Atul S. Khot
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Grokking the Functional Way FREE CHAPTER 2. Singletons, Factories, and Builders 3. Recursion and Chasing your Own Tail 4. Lazy Sequences – Being Lazy, Being Good 5. Taming Multiple Inheritance with Traits 6. Currying Favors with Your Code 7. Of Visitors and Chains of Responsibilities 8. Traversals – Mapping/Filtering/Folding/Reducing 9. Higher Order Functions 10. Actors and Message Passing 11. It's a Paradigm Shift Index

Lazy collections

All these combinators chaining are lovely, but there is a problem. For very large input data structures, this ends up creating intermediate copies.

Let's look at this aspect closely; you'll find that the solution is pretty revealing. Here is the Java code, just to set the stage:

public class LargeLists {
  public static void main(final String[] args) {
    final int take = 5;
    for (int i = 1000, n = 0; i < 1000000 && n < take; ++i) {
      final int j = i + 1;
      final int k = j * 2;
      if (k % 4 != 0) {
        System.out.println(k);
        ++n;
      }
    }
  }
}

Here, we iterate a range of numbers from 1000 to 1000000. And for each number, we add 1 and then multiply the result by 2. If the result is divisible by 4, we discard it. Otherwise, we print the first five numbers from the result.

For example:

scala> val list = (1000 to 1000000).toList
scala> list.map(_ + 1).map(_ * 2).filter(_ % 4 != 0).take(5)
res0: List[Int] = List(2002...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime