immutable

Erlang has single-assignment variables

“Erlang has single-assignment variables. As the name suggests, they can be given a value only once. If you try to change the value of a variable once it has been set, you’ll get an error.”

(“Single-assignment variables” are the same as val fields in Scala. Using them can make your code more like algebra.)

In Erlang, it’s OK to mutate state within an individual process alvin June 18, 2017 - 11:19am

“In Erlang (Akka), it’s OK to mutate state within an individual process (actor), but not for one process to tinker with the state of another process.”

Scala/FP Idiom: Update as You Copy, Don’t Mutate

“I’ve been imitated so well I’ve heard people copy my mistakes.”

Jimi Hendrix

Goals

In functional programming you don’t modify (mutate) existing objects, you create new objects with updated fields based on existing objects. For instance, last year my niece’s name was “Emily Maness,” so I could have created a Person instance to represent her, like this:

Disadvantages of Functional Programming

“People say that practicing Zen is difficult, but there is a misunderstanding as to why.”

Shunryu Suzuki,
Zen Mind, Beginner’s Mind

In the last chapter I looked at the benefits of functional programming, and as I showed, there are quite a few. In this chapter I’ll look at the potential drawbacks of FP.

Just as I did in the previous chapter, I’ll first cover the “drawbacks of functional programming in general”:

Rules for Programming in This Book

“Learn the rules like a pro, so you can
break them like an artist.”

Pablo Picasso

“Learn the rules, and then forget them.”
Haiku Master Matsuo Basho

Alright, that’s enough of the “preface” material, let’s get on with the book!

As I wrote earlier, I want to spare you the route I took of, “You Have to Learn Haskell to Learn Scala/FP,” but, I need to say that I did learn a valuable lesson by taking that route:

Functional programming: Everything is immutable

“Remember how weird it seemed when you first learned that a String in Java was immutable? Well, in functional programming it’s all like that. Everything is immutable.”

(From a discussion with a Java developer recently.)

How to drop the first matching element in a Scala sequence

Summary: This blog post shows one way to drop/filter the first matching element from a Scala sequence (Seq, List, Vector, Array, etc.). I don’t claim that the algorithm is efficient, but it does work.

Background

While creating some Scala test code earlier today I had an immutable list of toppings for a pizza, and I got into a situation where I wanted to remove the first instance of a topping.