Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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

Concise expression

You always want to be able to concisely express yourself. Let's try the following command to create a string:

scala> val list = List("One", "two", "three", "Four", "five")
list: List[String] = List(One, two, three, Four, five)

We have created a list of strings. Note that we neither had to specify the type of the list for this, nor any new keyword. We just expressed that we wanted a list assigned to a read-only variable.

Code reviews do a lot of good to a code base. I keep looking for places where I can replace a variable assignment with variable initialization. Refer to the following URL for an example: http://www.refactoring.com/catalog/replaceAssignmentWithInitialization.html.

Scala helps us with the val keyword. With the use of this keyword, we can establish the following:

  • The initial value of variable must be specified (it is impossible for the variable to remain uninitialized).
  • The value of variable cannot ever be changed again (there is one less moving part).

Why is this so important? A system with less moving parts is easier to understand and explain. You will be knowing that Google is well known for its less-moving-parts software. Let's try the following command to check for the uppercase in these characters:

scala> def hasUpperCaseChar(s: String) = s.exists(_.isUpper)
hasLowerCaseChar: (s: String)Boolean

What does s.exists(_.isUpper) do? In this code, I have a string and I am checking whether it has one or more uppercase characters.

Note that I need to look at each character of the string to arrive at an answer as output. However, I did not have to split the string into its constituent characters and then work on each character.

I am just expressing the algorithm. The algorithm involves iterating all characters. However, I did not write a loop. Instead, I expressed what I meant, concisely. Scala's strings are collections of characters. We can try the following command to make use of a filter method:

scala> list filter (hasUpperCaseChar)
res2: List[String] = List(One, Four)

Just like a string, List is again a collection, in this case, of strings. I used a list method, filter, to weed out elements that did not satisfy the predicate.

If we were to write this imperatively, we would need a nested loop (a loop within another loop). The first loop would take each string, and the inner loop would work on each character of the string. We would need a list to collect the matching elements.

Instead of lists, we just declared what we wanted to happen. However, at some point of time in the code the looping needs to happen! It does happen indeed, but behind the scenes and in the filter method.

The filter method is a higher order function that receives the hasUpperCaseChar function.

Let's say, in addition to this method, we want only those string elements that have a length greater than 3:

scala> list filter (x => hasLowerCaseChar(x) && x.size > 3)
res1: List[String] = List(Four)

We are again executing the algorithm; however, with a different match criteria. We are passing a function in the form of a function literal. Each element in the list is bound to x, and we run a check on x.

The preceding form of expression allows us to concisely express our intent. A large part of this flexibility comes from the idea of sending small computations around that are expressible without much ado. Welcome to functions!

You have been reading a chapter from
Scala Functional Programming Patterns
Published in: Dec 2015
Publisher:
ISBN-13: 9781783985845
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