Posts in the “scala” category

Functional programming books, comparison

Since I’ve written two functional programming books, I thought it might help to provide a comparison of them.

The short story is that both books have “limited technical jargon,” and as shown, The Little FP Book essentially has one purpose, which is to help Java/Kotlin/OOP developers learn functional programming as fast as possible, using a technique that I “discovered” over the last few years. Conversely, The Big FP Book covers many topics in great detail.

Here are links to the two books:

Scala: What do “effect” and “effectful” mean in functional programming?

When you get started with functional programming (FP) a common question you’ll have is, “What is an effect in functional programming?” You’ll hear advanced functional programmers use the words effects and effectful, but it can be hard to find a definition of what these terms mean.

Effects are related to monads (but don’t worry)

A first step in the process of understanding effects is to say that they’re related to monads, so you have to know just a wee bit about monads to understand effects.

But fear not, this is surprisingly simple. As I write in my book, Functional Programming, Simplified, a slight simplification is to say that in Scala, a monad is any class that implements the map and flatMap methods. Because of the way Scala for-expressions work, implementing those two methods lets instances of that class be chained together in for-expressions (i.e., for/yield expressions).

For OOP developers: The smallest, simplest functional programming book

Some of the computer programming books on the right side of this image are amazing, and I would never discourage anyone from reading the great ones.

But if you’re an object-oriented programming (OOP) developer who wants to start understanding functional programming (FP) over a weekend or a few nights of reading, that’s the goal of the new little book on the left: Learn Functional Programming The Fast Way. It takes you from Java/OOP to functional programming in the simplest possible step-by-step learning process.

FP for Java/Kotlin/OOP developers

I taught Java and OOP for many years, and have used other OOP languages like Kotlin, Python, and Flutter/Dart, so I understand both OOP and FP, and I think that helped to make this a simple book for learning FP.

I also wrote the FP book in the middle — Functional Programming, Simplified — and it’s about three times larger than the little book on the left. I based it on most of the FP books on the right, and it goes into many details that the book on the left doesn’t go into. It’s big, but it’s still easier than reading all the books on the right.

Learn Scala 3 for just $10

I’ve been slowly working on a series of new Scala programming books, and today I’m proud to announce the first of these:

Learn Scala 3 The Fast Way! (book cover)

Starting today you can buy the PDF version of Learn Scala 3 The Fast Way! for just ten dollars — $10 (USD) — at this Gumroad.com URL.

Book: Learn Functional Programming The Fast Way! (FP for OOP developers)

MARCH, 2023: This book was previously named, Learn Functional Programming Without Fear, but I have renamed it to Learn Functional Programming The Fast Way!. I think this name is more reflective of the ZIO and Cats Effect libraries being easier to learn than ever before (without having to know category theory), and the name is also consistent with my other book, Learn Scala 3 The Fast Way!.

NOV., 2022: My new book, Learn Functional Programming Without Fear, is currently an Amazon Java and functional programming #1 new release. The book is now available in three formats:

PDF Format
$10 (USD) on Gumroad.com

Learn Functional Programming The Fast Way! (PDF Version)

Paperback
$30 on Amazon

Learn Functional Programming The Fast Way (Paperback)

Kindle
$10 on Amazon

Learn Functional Programming The Fast Way! (Kindle Edition)

Scala: How to build control structures with types and call-by-name parameters

[toc]

(This article is an excerpt from the 1st Edition of the Scala Cookbook.)

To put what you’ve learned in this chapter to use, let’s create two examples. First, you’ll create a timer method that looks like a Scala control structure, and works like the Unix time command. Second, you’ll create another control structure that works like the Try/Success/Failure classes that were included with Scala in Scala 2.10.

Example 1: Creating a Scala Timer

On Unix systems you can run a time command (timex on some systems) to see how long commands take to execute:

$ time find . -name "*.scala"

Working with Parameterized Traits in Scala 3

This is a recipe from the Scala Cookbook (2nd Edition). This recipe is titled, Working with Parameterized Traits in Scala.

Problem

As you become more advanced in working with Scala types, you want to write a trait whose methods can be applied to generic types, or limited to other specific types.

Solution

Depending on your needs you can use type parameters or type members with traits. This example shows what a generic trait type parameter looks like:

Scala: How to define a generic method parameter that must extend a base type (bounds)

In today’s installation of “how to have fun with Scala,” if you want to define a Scala method that takes an input parameter, and that parameter has a generic type, and you further want to further declare that the parameter must extend some base type, use this syntax:

def getName[A <: RequiredBaseType](a: A) = ???

This example can be read as, “The parameter a has the generic type A, and A must be a subtype of RequiredBaseType.”

A complete example

As a concrete example of how this works, start with a simple base type, such as this Scala trait:

trait SentientBeing {
    def name: String
}

Next, extend that base trait with a few more traits:

trait AnimalWithLegs extends SentientBeing
trait TwoLeggedAnimal extends AnimalWithLegs
trait FourLeggedAnimal extends AnimalWithLegs

Then extend those with some concrete case classes:

case class Dog(name: String) extends FourLeggedAnimal
case class Person(name: String, age: Int) extends TwoLeggedAnimal
case class Snake(name: String) extends SentientBeing

Notice that Snake extends SentientBeing, but not AnimalWithLegs.

Now that you have all the types you need, define a method that takes a parameter that has a generic type that must extend some base type. To see how everything works, define it this way the first time:

def getName[A <: SentientBeing](a: A): String = a.name

Because the base type (or “super type”) is SentientBeing, all of these calls work just fine:

getName(Person("Fred", 20))
getName(Dog("Rover"))
getName(Snake("Noodles"))

(Copy and paste those into the Scala REPL if you want to verify they work as advertised.)

Now extend AnimalWithLegs

Next, change getName so the generic type A must be a subtype of AnimalWithLegs:

def getName[A <: AnimalWithLegs](a: A): String = a.name

Now, when you run the same three method calls again, you’ll see that the Snake example fails because it doesn’t extend AnimalWithLegs:

getName(Person("Fred", 20))
getName(Dog("Rover"))
getName(Snake("Noodles"))   //error

Here’s what the two sets of getName examples look like in the Scala REPL:

Show a Scala method with generic type parameter

(Right-click that image and select “View image” to see it larger.)

The “type parameter bounds” error

As shown, the second Snake example results in this error message:

scala> getName(Snake("Noodles"))
<console>:15: error: inferred type arguments [Snake] do not conform to method getName's 
type parameter bounds [A <: AnimalWithLegs]
       getName(Snake("Noodles"))
       ^
<console>:15: error: type mismatch;
 found   : Snake
 required: A
       getName(Snake("Noodles"))
                    ^

This is because the type Snake does not extend AnimalWithLegs. (At least not in my world.)

Technical matters: ‘A’ has an “upper bound”

Technically what’s happening here is that I’m defining A with an “upper bound.” Bounds let you place restrictions on type parameters, and in this example I’m saying, “A must be a subtype of the type AnimalWithLegs”:

def getName[A <: AnimalWithLegs](a: A): String = a.name

More generally, this is how you say, “A must be a subtype of B”:

A <: B

I write more about this topic in, An introduction to Scala Types, so please see that article for a few more details.

Scala 3 dates: How to calculate the difference between two dates (LocalDate, ChronoUnit)

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.10, Calculating The Difference Between Two Dates.

Problem

While using Scala (2 or 3), you need to determine the difference between two dates.

Scala Solution: Difference between two dates

If you need to determine the number of days between two dates, the DAYS enum constant of the java.time.temporal.ChronoUnit class is the easiest solution:

A Scala function to get the Unix epoch time for X days ago

As a brief note today, here’s a Scala function to get the Unix epoch time for X days ago:

/**
 * Returns a 10-digit Long (like 1585275929) representing the date/time.
 * Use it to get the time for 1 day ago, 2 days ago, etc. `0` will give
 * you the current time.
 */
def unixEpochTimeForNumberOfDaysAgo(numDaysAgo: Int): Long = {
    import java.time._
    val numDaysAgoDateTime: LocalDateTime = LocalDateTime.now().minusDays(numDaysAgo)
    val zdt: ZonedDateTime = numDaysAgoDateTime.atZone(ZoneId.of("America/Denver"))
    val numDaysAgoDateTimeInMillis = zdt.toInstant.toEpochMilli
    val unixEpochTime = numDaysAgoDateTimeInMillis / 1000L
    unixEpochTime
}

As shown in the comments, if you give it a 0 it will return the current epoch time. As shown by the function’s type signature, the function’s return type is a Long (which is a 64-bit two's complement integer).

Of course you can make the code shorter and better; I just wanted to show the steps in the approach using the Date/Time classes that were introduced in Java 8.

Scala 3: Creating New Date and Time Instances

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.9, Creating New Date and Time Instances.

Problem

You need to create new date and time instances using the Date and Time API that was introduced with Java 8.

Solution: Dates and times in Scala

Using the Java 8 API you can create new dates, times, and date/time values. Descriptions of common Java 8 Date and Time classes provides a description of some of the new classes you’ll use (from the java.time Javadoc), all of which work in the ISO-8601 calendar system.

Scala 3 Unions: Simulating Dynamic Typing with Union Types

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 23.9, Simulating Dynamic Typing with Union Types.

Problem

When using Scala 3, you have a situation where it would be helpful if a value could represent one of several different types, without requiring those types to be part of a class hierarchy. Because the types aren’t part of a class hierarchy, you’re essentially declaring them in a dynamic way, even though Scala is a statically-typed language.

Solution

In Scala 3, a union type is a value that can be one of several different types. Union types can be used in several ways.

In one use, union types let us write functions where a parameter can potentially be one of several different types. For example, this function, which implements the Perl definition of true and false, takes a parameter that can be either an Int or a String: