Posts in the “scala” category

Some Scala Exception ‘allCatch’ examples

At the time of this writing there aren’t many examples of the Scala Exception object allCatch method to be found, so I thought I’d share some examples here.

In each example I first show the "success" case, and then show the "failure" case. Other than that, I won’t explain these, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction:

A “Minority Report” Monte Carlo simulation in Scala

This article shares the source code for a Monte Carlo simulation that I wrote in Scala. It was inspired by the movie Minority Report, as well as my own experience.

Background

For the purposes of this simulation, imagine that you have three people that are each “right” roughly 80% of the time. For instance, if they take a test with 100 questions, each of the three individuals will get 80 of the questions right, although they may not get the same questions right or wrong. Given these three people, my question to several statisticians was, “If two of the people have the same answer to a given question, what are the odds that they are correct? Furthermore, if all three of them give the same answer to a question, what are the odds that they are right?”

Getting a random element from a list of elements in Scala

In working on projects like SARAH and other apps where I try to make a computer seem more “human,” I’ve been making my software reply to me in random ways. What I’ve found is that this ends up being an easily repeatable pattern, where you have a list of possible replies, and then you randomly return one of those replies.

The Scala for-loop translation scheme

If you're interested in the details of the translation scheme of a Scala for loop (for comprehension), here's a quick look at how a for loop is translated into, well, other code.

A simple Scala for loop

In a first example, we'll start with the following Scala class:

class Main {
  def foo { for(i <- 0 to 10) println(i) }
}

Next, I compile this class from the command line like this:

[toc hidden:1]

Starting to write an immutable singly-linked list in Scala

[toc]

For some examples in my new book on functional programming in Scala I needed to create a collection class of some sort. Conceptually an immutable, singly-linked list is relatively easy to grok, so I decided to create my own Scala list from scratch. This tutorial shows how I did that.

Background: What is a Cons cell?

The first time I learned about linked lists was in a language named Lisp. In Lisp, a linked list is created as a series of “Cons” cells. A cons cell is simple, it contains only two things:

How to use Scala’s sortInPlaceBy method on mutable sequences (ArrayBuffer, ArrayDeque)

[toc]

When I first looked at the sortInPlaceBy method that was introduced on mutable sequences in Scala 2.13, I couldn’t figure out exactly what it was supposed to do.

Unable to find any examples of “scala sortInPlaceBy” on planet Earth this evening (February 23, 2020), I had to resort to some actual work, and looked at the Scaladoc.

Reading the Scaladoc

This is what I see when I look at the Scaladoc for sortInPlaceBy on the ArrayBuffer:

def sortInPlaceBy[B](f: (A) => B)(implicit ord: Ordering[B]): ArrayBuffer.this.type

You can’t see by looking at that method what A is, so I scrolled up to the top of the page and saw this at the beginning of the Scaladoc:

How I came to write the Scala Cookbook

The funny thing about writing the Scala Cookbook is that it started as a whim. I was just about to leave for a vacation at the beach, and right before I turned off the computer a thought flashed in my mind, “I should contact the people at O’Reilly about writing a cookbook for Scala.” I then had a doubt that they would actually do it, but I applied the “What the heck” rule — i.e., “What the heck, what do I have to lose?” — and sent the email.

I dug around the internet for a few minutes, found the correct O’Reilly email address, sent them a message, turned off the computer, and drove to the beach. While I was at the beach the publisher wrote and said, “Love it, send me a full proposal!”

So if you’re thinking about doing something, but are afraid or uncertain about doing it ... apply the “What the heck” rule, and give it a shot. :)

How to create a large test Map in Scala (converting a sequence to a map)

If you ever need to create a large test Scala Map, I just used this approach and it worked fine:

val map = (for (i <- 1 to 5_000_000) yield (i, 10*i)).toMap

The initial results in the Scala REPL look like this:

val map: Map[Int, Int] = HashMap(4584205 -> 45842050, 2231874 -> 22318740, ...

The code works by creating a series of tuples with the yield expression, where each key is i, and each value is 10*i. Here are a couple of other ways to convert a Scala sequence to a map:

val map = Vector.range(0,1_000_000).map(i => (i, i*10)).toMap
val map = Vector.range(0,1_000_000).map(i => i -> i*10).toMap

A little Scala program to count lines of source code in the Scala Cookbook

As a little mini-project I wanted to count the number of lines of source code in the Second Edition of the Scala Cookbook as compared to the First Edition. To do this I wrote the following Scala program/script to count the lines between the ---- and .... sections in the AsciiDoc files that represent the old and new versions of the book:

Scala: How to create a list of alpha or alphanumeric characters

While looking for code on how to create a random string in Scala, I came across this article, which shows one approach for creating a random string. For my brain today, it also shows a nice way to create a list of alpha or alphanumeric characters.

For instance, to create a list of alphanumeric characters, use this approach:

Scala List class: methods, examples, and syntax

This page contains a large collection of examples of how to use the methods on the Scala List class.

The Scala List class as an immutable, linear, linked-list class. It’s very efficient when it makes sense for your algorithms to (a) prepend all new elements, (b) work with it in terms of its head and tail elements, and (c) use functional methods that traverse the list from beginning to end, such as filter, map, foldLeft, reduceLeft.

Scala: How to use higher-order functions (HOFs) with Option (instead of match expressions)

I originally wrote a long introduction to this article about how to work with the Scala Option, but I decided to keep that introduction for a future second article in this series. For this article I’ll just say:

  • idiomatic Scala code involves never using null values
  • because you never use nulls, it’s important for you to become an expert at using Option, Some, and None
  • initially you may want to use match expressions to handle Option values
  • as you become more proficient with Scala and Options, you’ll find that match expressions tend to be verbose
  • becoming proficient with higher-order functions (HOFs) like map, filter, fold, and many others are the cure for that verbosity

How to process multiple Option values in a Scala ‘for’ loop

My last edits to the Scala Cookbook were in June, 2013, and after all this time there aren’t many things I wish I had added to the Cookbook. Yesterday I ran into one thing that I don’t think I included in the Cookbook: How to process multiple Option values in a Scala for loop (for comprehension). Here’s a quick look at how to do this.

For the impatient

For those who just want to see a for comprehension that processes multiple input Option values, here you go:

How to use multiple Futures in a Scala for-comprehension

If you want to create multiple Scala Futures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.