Learning Recursion: A free book, by Alvin Alexander
As a brief note today, I just released the first version of a new, free book/booklet that I’ve titled Learning Recursion.
As a brief note today, I just released the first version of a new, free book/booklet that I’ve titled Learning Recursion.
NOV., 2022: My new book, Learn Functional Programming The Fast Way, is currently an Amazon Java and functional programming #1 new release. The book is now available in three formats:
PDF Format |
Paperback |
Kindle |
(Note: I don't have any immediate solutions in this article; it's more of a discussion of where I'm at today when looking at handling money/currency in Scala.)
As a quick note, I've started to look at handling money/currency in Scala, and I'm also starting to explore a couple of money/currency libraries.
Scala shell script FAQ: How do I create a Unix/Linux shell script to run a small Scala script?
If you want to run a Scala script as a Unix or Linux shell script -- such as hello.sh -- write your script like this:
This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.12, How to Parse Scala Strings Into Dates.
While using Scala (Scala 2 or 3), you need to parse a Scala String
into one of the date/time types introduced in Java 8, and still used in Java 11, 14, 17, etc.
If your String
is already in the expected format, pass it to the parse
method of the desired class. If the String
is not in the expected (default) format, create a formatter to define the format you want to accept. The following examples demonstrate the expected formats, and other solutions.
Scala list/sequence FAQ: How do I iterate over a Scala List
(or more generally, a Scala sequence) using the foreach
method or for
loop?
There are a number of ways to iterate over a Scala List
using the foreach
method — which is available to Scala sequences like List
, Array
, ArrayBuffer
, Vector
, Seq
, etc. — and the for
comprehension, and I'll show several of these solutions here.
Scala List
FAQ: How do I add elements to a Scala List
?
"How do I add elements to a Scala List
” is actually a bit of a trick question, because you can't add elements to a Scala List; it's an immutable data structure. If you’ve ever used the Java String
type, it’s just like that, you can’t mutate its elements.
That being said, in the following sections I’ll show what you can do.
The most common way to “add” elements to a Scala List
is to create a new List
from an existing List
by prepending elements to the existing list. We do this all the time in functional programming in Scala, and the general approach looks like this in the Scala REPL:
Scala math FAQ: How do I square a number in Scala, such as squaring an Int
, Double
, Long
, or Float
?
You can square a number in Scala in at least two different ways:
Math.pow
function or the scala.math.pow
functionScala FAQ: How can I use the startsWith
method on a Scala String
to match multiple possible patterns in a match
expression?
As shown in the following example, you can use the startsWith
method on a String
to match multiple possible patterns in a match
expression. startsWith
checks to see if a String
starts with the prefix (or substring) you specify, so although in these examples I use complete strings, you can also use regular expression patterns.
Scala FAQ: Using Scala, how do I generate random numbers without duplicate values, i.e., how do I generate a sequence of random, unique values?
To show the solution, here’s a Scala 3 function that generates a random sequence of unique integer values:
Scala date/time FAQ: How do I calculate the difference between two dates in Scala? That is, while using Scala 2 or Scala 3, you need to determine the difference between two dates. Also, you want to use the newest Java date/time API for this work, such as the date/time API in Java 8, 11, 14, 17, etc.
If you need to determine the number of days between two dates in Scala — or Java or Kotlin — the DAYS
enum constant of the java.time.temporal.ChronoUnit class provides the easiest solution:
When it comes to generating random strings with the scala.util.Random class, I haven’t figured out yet how to properly use the nextString
method. I’ve tried using it in several different ways, but I always get a string of question marks as output, like this:
Without any introduction or discussion, here’s a little Scala script I just wrote to read in a text file that contains stocks symbols, with one symbol per line, along with some blank lines; then convert those symbols to comma-separated output (CSV format) that I print to STDOUT:
I just had this problem in Scala where I wanted to concatenate two corresponding multiline strings into one final multiline string, such that the elements from the first string were always at the beginning of each line, and the lines from the second string were always second. (When I say corresponding, I mean that the two strings are of equal length.)
That is, given two Scala multiline strings like these:
If you want to get a value out of a Scala Option
type, there are a few ways to do it. In this article I’ll start by showing those approaches, and then discuss the approach of using the fold
method on an Option
(which I’ve seen discussed recently on Twitter).
As a first look at getting values out of an Option
, a common way to extract the value out of a Scala Option
is with a match
expression:
As a brief note today, here’s a Scala 3 function that counts the number of vowels in the String
it is given as input:
def countVowels(s: String): Int = val vowels = Set('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') s.count(vowels.contains)
Note that this works because as I have mentioned in other places, a Scala Set
can be used as a function — specifically as a predicate — and the count
function on the Scala sequence classes expects a predicate.
As a brief note today, here’s a Scala function to get the Unix epoch time for X days ago (5 days ago, 10 days ago, etc.):
/**
* 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.
UPDATE: The latest version of this code is at github.com/alvinj/TextPlottingUtils.
Creating an ASCII version of a Sparkline chart — also known as a Win/Loss chart — in Scala turned out to take just a few lines of code, as shown in this source code: