# Learning Functional Programming With Scala

### A summary of my journey learning Scala as a Java developer.

Join the DZone community and get the full member experience.

Join For FreeIn this blog post, I will write about my journey learning functional programming with Scala. I have a very object-oriented background in Java. To accompany me on this journey, I have decided to take this Coursera course.

I feel like it’s one thing to learn the theory and another thing to apply it. For this reason, I have also decided to build a working application after I completed my course. This is further detailed in the final chapters.

So my goals are:

- Complete the Coursera course assignments, which features university level content
- Write an application that reflects some of what I learned in this course

## Why Scala?

Several reasons.

- Interoperability with Java. This allows me to use my favorite libraries.
- I am genuinely interested in picking up more functional programming principles
- The job market in the Netherlands seems to need Scala developers
- According to StackOverflow 2020, it’s one of the highest paid languages :D
- In-demand + High Salary = Profit???

## Week 1

### Overall Syntax

The Scala language reminds me a lot of Kotlin. Types are written in a format like “var: Type”. A lot of things in Scala are implicit. For instance, the last expression of a function is its return.

### Everything Is an Expression

In Scala, everything is an expression. **Even if-statements! **This can be shocking for a Java developer.** **Luckily, I have some experience writing Kotlin, so this concept is not that new to me. Here’s an example of an if expression:

`xxxxxxxxxx`

`def abs(x: Double) = if (x > 0) x else -x`

### Functions, Blocks, and Lexical Scope

Functions can exist within functions with Scala. This can be used to hide parts of the surface area of a function, while still be able to re-use a private function. Here is an example of calculating the square root of a number by approximation and recursion. The ‘abs’, ‘isGood’, ‘improve’ and ‘sqrtIter’ functions are not accessible outside the scope of the functions.

`xxxxxxxxxx`

`def sqrt(x: Double): Double = {`

` def abs(x: Double) = if (x > 0) x else -x`

` def isGood(guess: Double, x: Double): Boolean =`

` abs(guess * guess - x) < 0.0001`

` def improve(guess: Double, x: Double) =`

` (guess + x / guess) / 2`

` def sqrtIter(x: Double, guess: Double): Double =`

` if (isGood(guess, x)) guess else sqrtIter(improve(guess, x), x)`

` sqrtIter(x, 1.0)`

`}`

### Def vs Val

Scala knows a big difference between definitions (defs) and values (vals). Defs are just definitions to what a variable should be evaluated against. This means that defs follow a lazy evaluation strategy that evaluates a def as it is needed. Vals on the other hand are evaluated on the spot. It properly reflects what the value of a variable is.

### Immutability

Functional programs embrace the idea of immutability. That means that you don’t mutate the state of data(e.g. `person.setName(String)`

), you return new versions of data(e.g. `person.copyWithName(String)`

). It seems inefficient, but it grants a heap of benefits.

**Thread Safe**: Immutable objects are thread safe by definition**No invalid state**: Once you validate the initial state of an object, you can be assured that this object always remains valid.**Simpler to test**: Because objects don’t change internally, they are by far easier to test, as their methods are always reproducible.

### Pure Functions

Functional programming embraces the idea that functions should be pure. That means that:

- The function must not rely on any code outside its scope, or hidden from view.
- The function must not modify any code outside its scope.
- The function must always evaluate to the same result, given the arguments are the same.

### Recursion

Recursion is not a new concept for me. But sometimes, I find it hard to wrap my head around it. Seeing that in pure functional programming there is no notion of a loop, this will be fun. In the exercises below, you will see me do the following using recursion:

- Implement the logic for Pascal’s Triangle
- Balance parentheses in a list of chars
- Counting the possibilities of change, given a certain list of coin types
- Calculate factorial

`xxxxxxxxxx`

`// Excercise 1`

`def pascal(c: Int, r: Int): Int = `

` if (c == 0 || r == c) 1 else pascal(c - 1, r - 1) + pascal(c, r - 1)`

`// Excercise 2`

`def balance(chars: List[Char]): Boolean = {`

` def loop(i: Int, amountOpen: Int): Boolean =`

` if (i >= chars.size) amountOpen == 0`

` else if (amountOpen < 0) false`

` else if (chars(i).equals('(')) loop(i + 1, amountOpen + 1)`

` else if (chars(i).equals(')')) loop(i + 1, amountOpen - 1)`

` else loop(i + 1, amountOpen)`

` `

` loop(0, 0)`

`}`

`//Exercise 3`

`def countChange(money: Int, coins: List[Int]): Int ={`

` if (money < 0 || coins.isEmpty)`

` 0`

` else if (money == 0)`

` 1`

` else`

` countChange(money - coins.head, coins) + countChange(money, coins.tail)`

`}`

`//Excercise 4`

`def factorial(n: Int): Int = `

` if (n == 0) 1 else n * factorial(n-1)`

### Tail Recursion

Recursion can generate a lot of load on your stack trace, causing stack overflow errors. Compilers and runtimes have implemented the concept of tail recursion to tackle some of these problems. Tail-recursion recycles the originating call graph, effectively making the call a for loop in disguise. Tail-recursion can only be applied if the recursive call is the last expression in a function and no other operators are applied to the recursive call. Beware, tail recursions introduce another level of cognitive load, as the function typically becomes harder to read.

## Week 2

### Higher-Order Functions

Higher-order functions are functions that take other functions as parameters and/or returns other functions. Here’s a quick example. Let’s say I have these functions:

`xxxxxxxxxx`

`// Returns the input`

`def identity(x: Int) = x`

`// Calculates cube of a number`

`def cube(x: Int) = x * x * x`

`// Calculates factorial of a number`

`def factorial(x: Int): Int =`

` if (x <= 1) 1 else x * factorial(x - 1)`

`//Sum function, adds up all ints between a and b`

`def sum(a: Int, b: Int): Int =`

` if (a > b) 0 else a + sum(a + 1, b)`

If I wanted to write a function that sums up all the cubes or factorials of a number, I can write something like this:

`xxxxxxxxxx`

`//Wraps all operands with a high-order function (the f parameter)`

`def sum(f: Int => Int, a: Int, b: Int): Int =`

` if (a > b) 0 else f(a) + sum(f, a + 1, b)`

`// Create a cubical sum of all ints from a to b`

`def sumCube(a: Int, b: Int) = sum(cube, a, b)`

`// Same for factorial`

`def sumFactorial(a: Int, b: Int) = sum(factorial, a, b)`

### Currying

Higher-order functions enable the concept of currying. *Insert lame joke about Indian food here*. It’s basically the concept of nesting returning functions. *A function can return a function that returns another function*.

`xxxxxxxxxx`

`// Creates a curried version of sum, where the`

`// first function is that to be applied to the input and the`

`// second function is the input`

`// (Int => Int) => (Int, Int) => Int`

`def sumCurry(f: Int => Int): (Int, Int) => Int = {`

` def sumF(a: Int, b: Int): Int =`

` if (a > b) 0 else f(a) + sumF(a + 1, b)`

` sumF`

`}`

`// Or with syntax sugar.....`

`def sumCurry(f: Int => Int)(a: Int, b: Int): Int =`

` if (a > b) 0 else f(a) + sumCurry(f)(a + 1, b)`

`// Sum can now be called like this. Pretty clean right?!`

`sumCurry(cube)(1, 6)`

`sumCurry(factorial)(1, 6)`

Now let’s see if we can rewrite factorial using the curry technique:

`xxxxxxxxxx`

`// Here is how I would curry a product function. I really like the word curry, btw.`

`def product(f: Int => Int)(a: Int, b: Int): Int =`

` if (a > b) 1 else f(a) * product(f)(a + 1, b)`

`// Factorial can now be written as follows`

`// Because factorial is by definition the product of all numbers 1 to n`

`def factorial(n: Int) = product(identity)(1, n)`

`// True!`

`factorial(5) == 120`

### Functional Sets

At the end of week 2, I implemented the concept of a functional set. The general notion of a functional set is that: *We represent a set by its characteristic function, i.e. its *`*contains*` *predicate. *This was a pretty fun assignment, as it really shows the elegance of functional programming

## Week 3

### Traits, Generics, Classes and Objects. Huh?!

In the course, I learned how to use the basic object-oriented primitives in Scala. I am very familiar with these concepts. However, in the course I noticed that the instructor also applied more declarative/functional principles to his code. For instance, he implemented a Binary Tree with classes and objects. However, he did not use imperative code to do so. Instead of updating a tree’s state, he would return a new instance of the tree. This by nature is **purely** functional. Wow. There are no side effects. The data is immutable. But, wow. Here is my example of an immutable List.

`xxxxxxxxxx`

`trait List[T] {`

` def isEmpty:Boolean`

` def head: T`

` def tail: List[T]`

`}`

`class Cons[T] (val head: T, val tail: List[T]) extends List[T] {`

` def isEmpty = false;`

`}`

`class Nil[T] extends List[T] {`

` def isEmpty = true`

` def head = throw new NoSuchElementException("Empty")`

` def tail = throw new NoSuchElementException("Empty")`

`}`

## Week 4

### Decomposition vs Pattern Matching

I use decomposition a lot. One of the problems I ran into while developing my own open-source project was the simplification of expressions. It turns out that the use of decomposition was not a feasible solution for what I wanted to do.

Pattern matching helps you decompose and navigate data structures in a very convenient and compact syntax. It looks like a Java switch statement, but is definitely not. **Switch could never! **The pattern matching feature looks very beautiful to me.

### Pattern Matching List

You can also pattern match against Lists, Strings and even RegEx patterns. Here I use pattern matching to implement the Insertion Sort. As you can see I match against the head and the tail of the list using ‘::’

`xxxxxxxxxx`

`def insertionSort(xs : List[Int]) : List[Int] = {`

` xs match{`

` case Nil => Nil`

` case x :: xs1 => insert(x, isort(xs1))`

` }`

` }`

`def insert(x : Int, xs : List[Int]) : List[Int] = {`

` xs match {`

` case Nil => List(x)`

` case y :: xs1 =>`

` if(y >= x) x :: xs`

` else y :: insert(x, xs1)`

` }`

`}`

## Week 5

### Huffman Encoding

In week 5, I implemented (and barely understood) Huffman coding. It is essentially a way to compress and decompress Strings by assigning every character in a String a weight. This weight represents how many times a character is used within a String. The characters are put into a certain code tree, which is contains Fork nodes and Leaf nodes.

Here is my solution(got an 8/10)

### Tuples

Tuples are a concept that does not exist in the Java world. They allow you to define a data structure that allows you to return multiple values from a function. This is one of my favourite parts of the Scala language. You can then destructure or pattern match against tuples like what I did in this Merge Sort implementation.

`def mergeSort(xs: List[Int]): List[Int] = {`

` val n = xs.length / 2`

` if (n == 0) xs`

` else {`

` val (firstHalf, secondHalf) = xs splitAt n`

` merge(mergeSort(firstHalf), mergeSort(secondHalf))`

` }`

`}`

`def merge(xs: List[Int], ys: List[Int]): List[Int] =`

` (xs, ys) match {`

` case (Nil, ys) => ys`

` case (xs, Nil) => xs`

` case (x :: xTail, y :: yTail) =>`

` if (x < y) x :: merge(xTail, ys) else y :: merge(yTail, xs)`

` }`

### Map, Filter, Reduce

I present to you, the Map-Filter-Reduce sandwich.

These three functions (along with forEach) form the basis of most functional operations.

**Map** allows you to transform data. **Filter** allows you to weed out unwanted data. **Reduce** allows you to summarize data.

These three methods are very powerful. And they form a basis to what you can do with sequences of data.

## Week 6: Scala on the Cloud

In my last week picking up Scala, I decided to build an application that runs on the cloud. I decided to do so in the form of a cloud function, considering that this is functional programming. I wanted to create a service that analyses the contents of Word, PDF and Text files and extracts key information about those files. The program would essentially perform sentiment analysis on the text content of the file and respond with the following contents:

- The language of the file
- The sentence with the highest magnitude
- The most positive sentence
- The most negative sentence
- The general tone of the document

This service will use the Google Cloud Natural Language API to perform the analysis.

### Used Functional Programming principles

I applied the following principles to my program, located here:

- The creation and decomposition of tuples
- Higher-order functions
- Currying
- RegEx pattern matching
- Nested functions
- Awesome Scala syntax sugar. Like that cool looking ‘else-try’ block

I feel like these principles reflect my favourite parts about functional programming.

## Conclusion

I feel like I have learned a lot about functional programming. At first, I didn’t like it, because of the initial learning curve. I felt everything was hidden behind some weird notation. After I understood what some of these notations meant, I grew a lot of appreciation for functional programming. I will definitely use more of these practices in my professional career. Who knows, I might even use Scala in a professional project.

### Connect with me ❤

I’m usually down for a spar session. Maybe even a new code homie?

- Check out my code on GitHub: https://github.com/RyanSusana
- Follow me on Twitter: https://twitter.com/RyanSusana
- Send me a message via my website: https://ryansusana.com

Published at DZone with permission of Ryan Susana. See the original article here.

Opinions expressed by DZone contributors are their own.

Comments