nil

This is a page from my book, Functional Programming, Simplified

Recursion: How to Write a ‘sum’ Function in Scala

With all of the images of the previous lesson firmly ingrained in your brain, let’s write a sum function using recursion!

Sketching the sum function signature

Given a List of integers, such as this one:

val list = List(1, 2, 3, 4)

let’s start tackling the problem in the usual way, by thinking, “Write the function signature first.”

How to use Lists in Scala match expressions

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.15, “How to use Lists in Scala match expressions.”

Problem

You know that a List data structure is a little different than other collection data structures. It’s built from “cons” cells and ends in a Nil element. You want to use this to your advantage when working with a match expression, such as when writing a recursive function.

Different ways to create and populate Lists in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 11.1, “Different Ways to Create and Populate a List in Scala”

Problem

You want to create and populate a List.

Solution

There are many ways to create and initially populate a List:

What is the difference between Nil and List() in Scala?

Scala FAQ: What is the difference between Nil and List() in Scala?

Short answer: There isn’t any difference, as shown in the Scala REPL:

scala> Nil == List()
res0: Boolean = true

It’s more “idiomatic Scala” Scala to use Nil rather than List(). For instance, I wrote code like this last night using Nil in a Scala match/case expression:

Scala List class examples: range, fill, tabulate, appending, foreach, more ...

Scala List FAQ: Can you share some Scala List class examples?

The Scala List class may be the most commonly used data structure in Scala applications. Therefore, it's very helpful to know how create lists, merge lists, select items from lists, operate on each element in a list, and so on.

In this tutorial, I'll try to share examples of the most common List operations (methods).