Categories
Tech

Scala Saturday – The contains and containsSlice Methods

Scala defines the contains method on all its collection classes.

Sets

Let’s say you have a set containing the nicknames of the guys in the band Rush, and you want to see whether a certain person is in the band. Just use contains:

val rush = Set("Dirk", "Lerxst", "Pratt")

val gotAlex = rush contains "Lerxst"
// gotAlex: Boolean = true
val gotAngus = rush contains "Angus"
// gotAngus: Boolean = false

Arrays, Lists, and Vectors (Oh, My!)

Seq and the sequence-like classes all define the contains method:

val rushSeq = Seq("Dirk", "Lerxst", "Pratt")
val rushA = Array("Dirk", "Lerxst", "Pratt")
val rushL = List("Dirk", "Lerxst", "Pratt")
val rushV = Vector("Dirk", "Lerxst", "Pratt")

val gotGene = rushSeq contains "Gene"
// gotGene: Boolean = false
val gotNeil = rushA contains "Pratt"
// gotNeil : Boolean = true
val gotAlex = rushL contains "Lerxst"
// gotAlex : Boolean = true
val gotPeter = rushV contains "Peter"
// gotPeter : Boolean = false

Sequences and the like also define a containsSlice method that takes a sequence and checks it is found in the collection. Order does matter, though:

val gotGedAndAl = rushSeq containsSlice Seq("Dirk", "Lerxst")
// gotGedAndAl: Boolean = true

// rushSeq has "Dirk" before "Lerxst", so the following fails
val gotAlAndGed = rushSeq containsSlice Seq("Lerxst", "Dirk")
// gotAlAndGed: Boolean = false

Strings

Because Scala just uses Java’s String class, we inherit the following from Java:

val gotX = "Lerxst" contains 'x'
// gotX : Boolean = true
val gotA = "Lerxst" contains 'A'
// gotA : Boolean = false

Java overloads contains to accept a String as well as a char:

val gotXs = "Lerxst" contains "xs"
// gotXs : Boolean = true
val gotAb = "Lerxst" contains "Ab"
// gotAb : Boolean = false

Because a String is also a sequence, Scala extends String with containsSlice if you prefer (perhaps for idiomatic reasons) to use it instead of contains. It can take a String or a sequence of Chars:

val gotXs = "Lerxst" containsSlice "xs"
// gotXs : Boolean = true
val gotXs = "Lerxst" containsSlice Seq('x', 's')
// gotXs : Boolean = true

Maps

Map has a contains method, and it operates on the Map‘s keys, not its values or its key-value pairs:

val rushM = Map(
  "Dirk" -> "bass",
  "Lerxst" -> "guitar",
  "Pratt" -> "drums")
val gotGed = rushM contains "Dirk"
// val gotGed : bool = true

To look among a Map‘s values, get the valuesIterator first. I’m not wild about this interface. It should have been values instead, but values returns an Iterable, which has no contains method:

val gotDrummer = rushM.valuesIterator contains "drums"
// gotDrummer: Boolean = true
val gotSitarist = rushM.valuesIterator contains "sitar"
// gotSitarist: Boolean = false

There is no contains variant that searches on a key-value pair. You can define an extension method containsPair:

object MapExt {
  implicit class RichMap[A,B](val m: Map[A,B]) extends AnyVal {
    def containsPair(p: (A,B)): Boolean =
      m get p._1 contains p._2
  }
}

import MapExt._

val gotGedOnBass = rushM containsPair ("Dirk" -> "bass")
// gotGedOnBass: Boolean = true

val gotGedOnFlute = rushM containsPair ("Dirk" -> "flute")
// gotGedOnFlute: Boolean = false

val gotGeorgeOnSitar = rushM containsPair ("George" -> "sitar")
// gotGeorgeOnSitar: Boolean = false
Categories
Tech

F# Friday – The (Elusive) contains Function

Let’s say you have a set containing the nicknames of the guys in the band Rush, and you want to see whether a certain person is in the band. No problem:

let rush = set ["Dirk"; "Lerxst"; "Pratt"]

let gotAlex = rush |> Set.contains "Lerxst"
// val gotAlex : bool = true
let gotAngus = rush |> Set.contains "Angus"
// val gotAngus : bool = false

If, on the other hand, you have the same values in a list, things don’t go so well:

let rush = ["Dirk"; "Lerxst"; "Pratt"]

let gotAlex = rush |> List.contains "Lerxst"
//   rush |> List.contains "Lerxst"
//   -------------^^^^^^^^
//
// error FS0039: The value, constructor,
// namespace or type 'contains' is not defined

Huh? No contains function in the List module? OK, what if you try it with an array?

let rush = [|"Dirk"; "Lerxst"; "Pratt"|]

let gotAlex = rush |> Array.contains "Lerxst"
//   rush |> Array.contains "Lerxst"
//   --------------^^^^^^^^
//
// error FS0039: The value, constructor,
// namespace or type 'contains' is not defined

Still AOL! Don’t look for it in the Seq module either; it’s not there.

Lists, Arrays, and Sequences (Oh My!)

Well, there are two ways around these limitations. First, contains is just a special case of exists, which is defined in all the collections modules. As F#’s modules are open, it’s easy enough to add contains to your projects:

module List =
    let contains x = List.exists ((=) x)

module Array =
    let contains x = Array.exists ((=) x)

module Seq =
    let contains x = Seq.exists ((=) x)

And voila, all of the following now work fine:

let rushL = ["Dirk"; "Lerxst"; "Pratt"]
let rushA = [|"Dirk"; "Lerxst"; "Pratt"|]
let rushSeq = seq ["Dirk"; "Lerxst"; "Pratt"]

let gotAlex = rushL |> List.contains "Lerxst"
// val gotAlex : bool = true
let gotNeil = rushA |> Array.contains "Pratt"
// val gotNeil : bool = true
let gotGene = rushSeq |> Seq.contains "Gene"
//val gotGene : bool = false

// Lists and arrays are sequences!
let gotGeddy = rushL |> Seq.contains "Dirk"
// val gotGeddy : bool = true
let gotPeter = rushA |> Seq.contains "Peter"
// val gotPeter : bool = false

The other approach you could take is to use LINQ. Opening the System.Linq namespace grants you access to all of the Enumerable extension methods. That means that all of the following work:

open System.Linq

let rushL = ["Dirk"; "Lerxst"; "Pratt"]
let rushA = [|"Dirk"; "Lerxst"; "Pratt"|]
let rushSet = set ["Dirk"; "Lerxst"; "Pratt"]
let rushSeq = seq ["Dirk"; "Lerxst"; "Pratt"]

let gotAlex = rushL.Contains "Lerxst"
// val gotAlex : bool = true
let gotNeil = rushA.Contains "Pratt"
// val gotNeil : bool = true
let gotGeddy = rushSet.Contains "Dirk"
// val gotGeddy : bool = true
let gotGene = rushSeq.Contains "Gene"
//val gotGene : bool = false

If you prefer your F# to be a little more idiomatic, you can define new module functions that delegate to LINQ rather than using exists:

open System.Linq

module List =
    let contains x (l: 'T list) = l.Contains x

module Array =
    let contains x (a : 'T array) = a.Contains x

module Seq =
    let contains x (s : 'T seq) = s.Contains x

Strings

Similarly, the String module does not contain a contains function either. You can take the same tack as you did with the other collections and define contains in terms of exists:

module String =
    let contains x = String.exists ((=) x)

let gotX = "Lerxst" |> String.contains 'x'
// val gotX : bool = true
let gotA = "Lerxst" |> Seq.contains 'A'
// val gotA : bool = false

Or you likewise have the option of using LINQ:

open System.Linq

module String
    // String.Contains can take a char or a string,
    // so you have to specify which
    let contains (c : char) (s : string) = s.Contains c

let gotX = "Lerxst" |> String.contains 'x'
// val gotX : bool = true
let gotA = "Lerxst" |> Seq.contains 'A'
// val gotA : bool = false

Of course, because String.Contains is overloaded to take either a string or a char, you have a little more flexibility if you call it as a method on the string rather than an F# function:

"Pratt".Contains("tt")
// val it : bool = true
"Pratt".Contains('p')
// val it : bool = false

Maps

Finally, the Map module does have a containsKey function …

let rushM = ["Dirk", "bass"; "Lerxst", "guitar"; "Pratt", "drums"]
            |> Map.ofList
let gotGed = rushM |> Map.containsKey "Dirk"
// val gotGed : bool = true

… but no containsValue or contains functions:

rushM |> Map.contains "Dirk"
//   rushM |> Map.contains "Dirk"
//   -------------^^^^^^^^
//
// stdin(5,14): error FS0039: The value, constructor,
// namespace or type 'contains' is not defined

rushM |> Map.contains ("Dirk", "bass")

//   rushM |> Map.contains ("Dirk", "bass")
//   -------------^^^^^^^^
// 
// stdin(7,14): error FS0039: The value, constructor,
// namespace or type 'contains' is not defined

rushM |> Map.containsValue "bass"
//   rushM |> Map.containsValue "bass"
//   -------------^^^^^^^^^^^^^
// 
// stdin(9,14): error FS0039: The value, constructor,
// namespace or type 'containsValue' is not defined

As with the other collections, we can define contains and containsValue in terms of exists:

module Map =
    let contains (k,v) = Map.exists (fun x y -> (x,y) = (k,v))
    let containsValue v = Map.exists (fun _ x -> x = v)

let gotDirkOnBass = rushM |> Map.contains ("Dirk", "bass")
// val gotDirkOnBass : bool = true
let gotBassPlayer = rushM |> Map.containsValue "bass"
// val gotBassPlayer : bool = true

You could alternatively define contains in terms of LINQ, but it is more verbose and provides no advantage over Map.exists. Because neither LINQ nor the IDictionary interface provide a ContainsValue method, defining Map.containsValue is certainly more verbose and a little more involved than simply using Map.exists.

NOTE: As of this writing, F# 3.1 is the latest version. According to UserVoice, F# 4.0 adds the missing contains function to the List, Array, and Seq modules, along with a few other useful functions.

Categories
Tech

Scala Saturday — The exists Method

The Scala collections API defines the exists method on all its classes. The exists method takes a predicate. If any item in the collection meets the predicate, exists returns true. Otherwise, it returns false.

List(1, 3, 5, 7, 9) exists { _ == 3 }
// res0: Boolean = true

(1 to 12) exists { _ < 1 }
// res1: Boolean = false

Array(1, 3, 5, 7, 9) exists { _ % 3 == 0 }
// res2: Boolean = true

Set(1, 3, 5, 7, 9) exists { _ % 2 == 0 }
// res3: Boolean = false

Strings are collections/sequences of characters, so both of the following are valid:

"asdf" exists { _ == 's' }
// res4: Boolean = true

"asdf" exists { _ == 'b' }
// res5: Boolean = false

The Map module also defines an exists function, but the predicate takes two inputs: one for the key and one for the value.

val m = Map("A" -> 1, "B" -> 2, "C" -> 4, "D" -> 8)
m exists { _ == "D" -> 8 }
// res6: Boolean = true

And of course, if you want to test only the key or only the value, only test the first field or the second field, respectively, of the input tuple.

m exists { _._1 == "Z" }
// res7: Boolean = false

m exists { _._2 == 2 }
// res8: Boolean = true

Option also defines an exists method. If the option is Some, then exists applies the predicate to the value in the Some instance and returns the result. If the option is None, then exists always returns false (as the REPL is kind enough to point out to us).

Some("X") exists { _ == "X" }
// res9: Boolean = true

Some("X") exists { _ == "Y" }
// res10: Boolean = false

None exists { _ == "X" }
// <console>:8: warning:
// comparing values of types
// Nothing and String using
// `==' will always yield false
//      None exists { _ == "X" }
//                      ^
// res11: Boolean = false
Categories
Tech

F# Friday — The exists Function

The collections modules in F# all define an exists function that takes a predicate and an instance of the collection. If any item in the collection meets the predicate, exists returns true. Otherwise, it returns false.

[1..12] |> List.exists (fun n -> n = 11)
// val it : bool = true

[|1..12|] |> Array.exists (fun n -> n < 1)
// val it : bool = false

set [1..12] |> Set.exists (fun n -> n % 2 = 0)
// val it : bool = true

seq [1..12] |> Seq.exists (fun n -> n > 20)
// val it : bool = false

Of course, as lists, arrays, and sets are all sequences, we can use Seq.exists for all of them:

[1..12] |> Seq.exists (fun n -> n = 11)
// val it : bool = true

[|1..12|] |> Seq.exists (fun n -> n < 1)
// val it : bool = false

set [1..12] |> Seq.exists (fun n -> n % 2 = 0)
// val it : bool = true

Strings are collections/sequences of characters, so both of the following are valid:

"asdf" |> String.exists (fun c -> c = 's')
// val it : bool = true

"asdf" |> Seq.exists (fun c -> c = 'b')
// val it : bool = false

The Map module also defines an exists function, but the predicate takes two inputs: one for the key and one for the value.

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun k v -> (k,v) = ("C",4))
// val it : bool = true

And of course, if you want to test only the key or only the value, name the input of no interest with an underscore in the lambda.

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun k _ -> k = "Z")
// val it : bool = false

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun _ v -> v = 2)
// val it : bool = true

The Option module also defines an exists function. If the option is Some, then exists applies the predicate to the value in the Some instance and returns the result. If the option is None, then exists always returns false.

Some "X" |> Option.exists (fun s -> s = "X")
// val it : bool = true

Some "X" |> Option.exists (fun s -> s = "Y")
// val it : bool = false

None |> Option.exists (fun s -> s = "X")
// val it : bool = false
Categories
Tech

F# Fridays and Scala Saturdays

I’ve decided to take a page out of Steven Proctor‘s book–well, blog actually. He has been doing Ruby Tuesday, a weekly series of posts on Ruby. Each week he examines a certain function in the language. He also publishes a counterpart series, Erlang Thursday, in which he does the same thing in—you guessed it—APL.

Kidding. It’s Erlang, of course.

The nice thing about these series is that Proctor examines the same or similar features in both languages. You get to see the application of a concept in Ruby, and then a couple of days later, the same concept in Erlang. It’s interesting to note the similarities and differences in the two languages.

In like fashion, I am beginning two series: F# Friday and Scala Saturday. I’ll probably borrow (i.e., steal blind) a number of Proctor’s ideas, that is, cover the same sort of functions he has. I thank Mr. Proctor for the idea and Mrs. Ezell, my middle school grammar teacher, for alliteration.

Categories
General

Hurts Me More Than It Hurts You

I try, as I suppose all parents do, to teach my kids first by telling them, warning them of consequences that are likely to come from certain foolish or careless behavior. Then if the message never does seem to get through, I like to try to bring it home by arranging for my kids get a minor taste of those consequences.

My boys received new tablets for Christmas. And regarding these tablets, as I have with other electronics they already own, I have tried to impress upon them both, “Make sure you put these away when you’re finished playing with them. You cannot leave these things lying around just anywhere, such as in the floor or in a chair or on the couch. Someone will not see them and then step on or sit on them. Then your nice, new tablet will be nice and broken.”

Well, where do you imagine that I found one of those tablets? On the couch, just waiting to be sat on. I decided that this was one of those times that I should let my kids get a brief taste of the consequences I had warned them about. I took the tablet and hid it, waiting for the owner (I didn’t bother to check whose it was) to come looking for it.

Yesterday morning, I heard my youngest—he’s four—asking my wife whether she knew the whereabouts of his tablet, and I thought, “It’s time to strike.” He eventually came asking me if I had seen it, and I decided I would use Nathan’s approach to King David in II Samuel 12 and manufacture a little story to illustrate to my son his folly.

I told him, “Son, there was a tablet lying on the couch—I don’t know whose it was—and I didn’t see it. I ended up sitting on it, and it cracked. I’m sorry, son. No more tablet.” As I was telling him this, I could see his countenance falling, and his eyes beginning to well with tears. Finally, his eyes dropped to the floor, and in perhaps the most pitiable voice I’ve ever heard, he whimpered, “I guess it was mine.”

He was absolutely crushed! And I nearly was, too!

I managed to hold it together long enough to tell him, “OK, son, I’ve got your tablet. It’s fine; it’s not really broken.” I told him that there was not harm done this time, but next time he may not be so lucky. “Come on, son. Let’s go get your tablet.”

After we retrieved his perfectly fine tablet, I could tell he was still upset, and frankly so was I. I scooped him up and held him. I tried to explain why I did what I did: “Son, I just want you to learn to take care of your things. I don’t want to have to give you the news, for real next time, that your tablet is actually broken.” I don’t know whom I was trying to console more: him or myself. At any rate, my hope is that this temporary feeling of loss will stick with him, and the next time—every time, for that matter—he goes to put his tablet down, he’ll remember that time it was “broken” and think to put it someplace safe.

OK, folks, let’s face it. That old saying parents have told their kids about administering punishment, “It hurts me more than it hurts you”: yeah, that’s pretty much bunk. Sorry, maybe I’m a callous jerk, but when I’m swatting a behind for some infraction, if it hurts me more than it hurts them, I ain’t doin’ it right. However, in this case with my four-year-old, perhaps that old lie was actually true. The very reason I’m writing this is because every time I replay the scene in my mind, seeing that utterly devastated look on my son’s face, hearing the abject defeat in his voice, I’m still moved almost to tears.

It reminds me of another occasion. My now ten-year-old daughter was probably two at the time. I can’t remember what she had done. It was not outright rebellion, to the best of my recollection, but it was either something I had just told her not to do or had told her several times in recent days not to do. Whatever it was, I decided a quick, stinging swat to the bare thigh was in order. It took her by surprise, and she turned and looked at me with genuine hurt as she rubbed her thigh. Then she said it: “Daddy.”

I had to choke back a sob.

I don’t know quite how to describe the combination of the look on her face and the tone in her voice. It certainly was not defiance. It also wasn’t as if she thought, “Well, yeah, I guess I deserved that.” It was, I think, disappointment. It was as if she were saying, “You didn’t really have to do that, did you? I didn’t mean any harm.” It was heartbreaking!

I have had no trouble meting out punishment at other times—punishment that, I’m sure, my kids thought they didn’t quite deserve. But for some reason, this time was different. The fact that she seemed genuinely disappointed, apparently in me, that I thought she deserved such a punishment, was almost too much to bear.

“This hurts me more than it does you.” Most of the time, complete rubbish. Still, even a hardened, old disciplinarian like me has to admit that, on occasion, it does perhaps hurt me at least as much as it hurts them.

Categories
Tech

FPOO Chapter 6 in Scala

This is the second in a series of articles working though the exercises in Brian Marick’s Functional Programming for the Object-Oriented Programmer, but implemented in Scala instead of Clojure. (Hat tip to Mr. Avdi Grimm for the idea.) The full source code is available on GitHub. Read the previous article on the exercises in chapter 1.

Exercise 1: Factorial

We did a factorial function in chapter 1, but Mr. Marick introduces us to recursion in chapter 6. Therefore we’ll use recursion in this implementation, in particular, recursion that uses the following form:

def factorial(n: Int): Int = n match {
  case endingCase => endingValue(n)
  case _ => combine(n, factorial(smallerValFromN(n)))
}

As with last time, the test first using the table-driven method:

class FactorialSpec extends UnitSpec with TableDrivenPropertyChecks {
  "Chapter 6, Exercise 1: factorial" should "compute the factorial, i.e., n!, of a given integer n >= 0" in {
    val factorials = Table(
      ("n", "fact"),
      (0,   1),
      (1,   1),
      (2,   2),
      (3,   6),
      (4,  24),
      (5, 120)
    )

    forAll (factorials) { (n: Int, fact: Int) =>
      whenever (n >= 0) {
        factorial(n) should be (fact)
      }
    }
  }
}

… and now the implementation:

object Chapter06 {
  def factorial(n: Int): Int = n match {
    case 0 => 1
    case _ => n * factorial(n - 1)
  }
}

In one of Mr. Marick’s hints, he suggests not worrying about the zero case, but it’s easy enough. Another case to handle is a negative n, which I handled in the exercises for chapter 1, but decided not to bother with this time.

Exercise 2: A Second Factorial

Yet another implementation of factorial, but this time we use a slightly different recursive form:

def factorial(n: Int): Int = {
  def factorialAcc(n: Int, soFar: Int) = n match {
    case endingCase => soFar
    case _ => factorialAcc(smallerValFromN(n), combine(n, soFar))
  }
  factorialAcc(n, 1)
}

My test is almost exactly the same as the test for Exercise #1:

class Factorial2Spec extends UnitSpec with TableDrivenPropertyChecks {
  "Chapter 6, Exercise 2: factorial2" should "compute the factorial, i.e., n!, of a given integer n >= 0" in {
    val factorials = Table(
      ("n", "fact"),
      (0,   1),
      (1,   1),
      (2,   2),
      (3,   6),
      (4,  24),
      (5, 120)
    )

    forAll (factorials) { (n: Int, fact: Int) =>
      whenever (n >= 0) {
        factorial2(n) should be (fact)
      }
    }
  }
}

The implementation using the second form of recursion is as follows:

object Chapter06 {
  def factorial2(n: Int): Int = {
    @tailrec
    def fact_(something: Int, soFar: Int): Int = something match {
      case 0 => soFar
      case _ => fact_(something - 1, something * soFar)
    }
    fact_(n, 1)
  }
}

Two points about this form of recursion: First, this form uses an accumulator, a value that we use to build our way up to the final answer with each step of the recursion (in contrast to the first pattern, which piles up a stack of recursive calls until the end case, at which point we combine the return values of the entire stack). The soFar parameter of the fact_ inner function serves as the accumulator in the implementation above.

Second, this form of recursion uses tail recursion, wherein the return value on the recursive branch is the recursive call and nothing else. The call to fact_ in the recursive branch is called a tail call. The compiler can optimize tail recursion as a loop. As Mr. Marick informs us, in Clojure, one must employ the recur function to make tail call optimization happen. Similarly, Scala requires the @tailrec annotation, as highlighted above.

Exercise 3: Summing a Sequence of Numbers

This exercise is to implement a function that sums the number of a sequence together using the second pattern of recursion, i.e., using a tail call with an accumulator. The test is as follows:

class SumSequenceSpec extends UnitSpec {
  "Chapter 6, Exercise 3: sumSequence" should "sum all of the elements in a sequence starting with an initial value" in {
    sumSequence(Seq(2, 4, 6, 8), 0) should be (20)
  }
  it should "return 0 if the sequence is empty" in {
    sumSequence(Seq[Int](), 0) should be (0)
  }
}

… and the implementation:

object Chapter06 {
  @tailrec
  def sumSequence[T](seq: Seq[T], init: T)(implicit n: Numeric[T]): T = seq match {
    case Seq() => init
    case _ => sumSequence(seq.tail, n.plus(init, seq.head))
  }
}

This time, instead of using an inner function to do the recursion, sumSequence itself takes an accumulator, init. Consequently, I can annotate it with @tailrec. Also I employed the trick from the exercises in chapter 1 of using an implicit Numeric parameter to enforce the constraint that this only works for sequences of numbers.

Exercise 4: Multiplying a Sequence of Numbers

The only difference between this exercise and the last one is the operation we perform on the sequence elements. Here’s the test:

class ProdSequenceSpec extends UnitSpec {
  "Chapter 6, Exercise 4: prodSequence" should "multiply all of the elements in a sequence starting with an initial value" in {
    prodSequence(Seq(2, 4, 6, 8), 1) should be (384)
  }
  it should "return 1 if the sequence is empty" in {
    prodSequence(Seq[Int](), 1) should be (1)
  }
}

… and here’s the implementation:

object Chapter06 {
  @tailrec
  def prodSequence[T](seq: Seq[T], init: T)(implicit n: Numeric[T]): T = seq match {
    case Seq() => init
    case _ => prodSequence(seq.tail, n.times(init, seq.head))
  }
}

Exercise 4a: Extracting the Combiner

Mr. Marick notes that the only difference between exercises 3 and 4 is the operation performed on the elements in the sequence, or the combiner, to borrow the parlance in Mr. Marick’s pseudocode. The test reflects the difference in the way we call the function now by passing in the combiner as a parameter with the sequence:

class ReduceSequenceSpec extends UnitSpec {
  val op = (a: Int, b: Int) => a * b
  "Chapter 6, Exercise 4a: reduceSequence" should "apply an operation all of the elements in a sequence starting with an initial value" in {
    reduceSequence(op, Seq(2, 4, 6, 8), 1) should be (384)
  }
  it should "return init if the sequence is empty" in {
    reduceSequence(op, Seq[Int](), 1) should be (1)
  }
}

And here is how I have implemented it:

object Chapter06 {
  @tailrec
  def reduceSequence[A](op: (A, A) => A, seq: Seq[A], init: A): A = seq match {
    case Seq() => init
    case _ => reduceSequence(op, seq.tail, op(seq.head, init))
  }
}

That works, but there is a problem. Exercise 5 exposes it.

Exercise 5: Building a Map from a Sequence

Mr. Marick stresses that we should perform this next exercise without changing the implementation of reduceSequence. So let’s try with our test:

class ReduceSequenceVecToMapSpec extends UnitSpec {
  val op = (a: String, b: Map[String, Int]) => b + (a -> 0)
  "Chapter 6, Exercise 5: reduceSequence" should "convert a sequence of strings into a map keyed to those strings with values of zero" in {
    reduceSequence(op, Vector("a", "b", "c"), Map[String, Int]()) should be (Map("a" -> 0, "b" -> 0, "c" -> 0))
  }
  it should "return init if the sequence is empty" in {
    reduceSequence(op, Seq[String](), Map[String, Int]()) should be (Map[String, Int]())
  }
  val op2 = (a: String, b: Map[String, Int]) => b + (a -> (b.size + 1))
  "Chapter 6, Exercise 5a: reduceSequence" should "convert a sequence of strings into a map keyed to those strings with values that increment by 1" in {
    reduceSequence(op2, Vector("a", "b", "c"), Map[String, Int]()) should be (Map("a" -> 1, "b" -> 2, "c" -> 3))
  }
}

And now the error bites us. Clojure is dynamically typed, so the implementation we would have come up with in Clojure probably would still work for this exercise if it worked for the last one.

Scala, in contrast, is statically typed. Our implementation worked in the last exercise because the type of the elements in the input sequence is the same as the type of the return value: we’re taking a sequence of integers and multiplying/adding them together, which produces an integer. In this exercise, however, we need to take a sequence of strings and produce a map—ain’t nothin’ the same about them types there! Therefore the implementation has to change to allow for a return type different from the type of the input elements:

object Chapter06 {
  @tailrec
  def reduceSequence[A, B](op: (A, B) => B, seq: Seq[A], init: B): B = seq match {
    case Seq() => init
    case _ => reduceSequence(op, seq.tail, op(seq.head, init))
  }
}

That wraps up chapter 6. Exercises from later chapters to come in future posts.

Categories
Tech

FPOO Chapter 1 in Scala

This is the first in a series of articles working though the exercises in Brian Marick’s Functional Programming for the Object-Oriented Programmer, but implemented in Scala instead of Clojure. (Hat tip to Mr. Avdi Grimm for the idea.) The full source code is available on GitHub.

For each exercise, I first wrote a specification in ScalaTest and then wrote the implementation. I followed the recommendation of the ScalaTest user guide and created the UnitSpec base class that all of my specs extend:

class UnitSpec extends FlatSpec
  with Matchers
  with OptionValues
  with Inside

Exercise 1: second

First the test:

class SecondSpec extends UnitSpec {
  "Exercise 1: second" should "return the second item in a given list" in {
    val list = List("Lorem", "ipsum", "dolor", "sit", "amet")
    second(list) should be ("ipsum")
  }
  it should "throw IndexOutOfBoundsException if called on a list with fewer than 2 elements" in {
    val listOf1 = List("sole")
    a [IndexOutOfBoundsException] should be thrownBy {
      second(listOf1)
    }
  }
}

… and then the implementation—pretty simple:

object Chapter01 {
  def second[A](list: List[A]): A = list(1)
}

Exercise 2: third

Mr. Marick asked for two implementations. First the tests, then the implementations:

class ThirdSpec extends UnitSpec {
  "Exercise 2a: third" should "return the third item in a given list" in {
    val list = List("Lorem", "ipsum", "dolor", "sit", "amet")
    third(list) should be ("dolor")
  }
  it should "throw IndexOutOfBoundsException if called on a list with fewer than 3 elements" in {
    val listOf2 = List("penultimate", "ultimate")
    a [IndexOutOfBoundsException] should be thrownBy {
      third(listOf2)
    }
  }

  "Exercise 2b: third2" should "return the third item in a given list" in {
    val list = List("Lorem", "ipsum", "dolor", "sit", "amet")
    third2(list) should be ("dolor")
  }
  it should "throw NoSuchElementException if called on a list with fewer than 3 elements" in {
    val listOf2 = List("penultimate", "ultimate")
    a [NoSuchElementException] should be thrownBy {
      third2(listOf2)
    }
  }
}

Again, both are pretty simple:

object Chapter01 {
  def third[A](list: List[A]): A = list(2)
  def third2[A](list: List[A]): A = list.tail.tail.head
}

Exercise 3: addSquares

The test for this one is pretty straightforward:

class AddSquaresSpec extends UnitSpec {
  "Exercise 3: addSquares" should "square each item in a list and sum them" in {
    val list = List(1, 2, 5)
    addSquares(list) should be (30)
  }
  it should "return 0 if called on an empty list" in {
    val emptyList = List[Int]()
    addSquares(emptyList) should be (0)
  }
}

I found the implementation somewhat challenging because I was not sure how to limit my input parameter to be a list of numbers. A second argument list that takes a single implicit parameter did the trick:

object Chapter01 {
  def addSquares[T](list: List[T])(implicit n: Numeric[T]): T =
    list.map( x => n.times(x, x) ).sum
}

Exercise 4: bizarreFactorial

In order to have a list of several inputs and the expected result for each, I used ScalaTest’s TableDrivenPropertyChecks trait.

class BizarreFactorialSpec extends UnitSpec with TableDrivenPropertyChecks {
  "Exercise 4: bizarreFactorial" should "compute the factorial, i.e., n!, of a given integer n >= 0" in {
    val factorials = Table(
      ("n", "factorial"),
      (0,   1),
      (1,   1),
      (2,   2),
      (3,   6),
      (4,  24),
      (5, 120)
    )

    forAll (factorials) { (n: Int, factorial: Int) =>
      whenever (n >= 0) {
        bizarreFactorial(n) should be (factorial)
      }
    }
  }
}

Mr. Marick’s constraints were to use apply, but not to use either iteration or recursion. Scala has apply, but its purpose is to allow you to use an object as if it were a function. Clojure’s apply is effectively used more like the way Scala uses reduce on collections. Consequently, I could have implemented bizarreFactorial this way:

object Chapter01 {
  def bizarreFactorial(n: Int): Int = n match {
    case x if x < 0 => throw new IllegalArgumentException("Factorial only works for positive integers")
    case 0 => 1
    case _ => 1 to n reduce (_ * _)
  }
}

But Scala has a shorthand for that: product (like sum in Exercise 3 above), which yields slightly more readable code.

object Chapter01 {
  def bizarreFactorial(n: Int): Int = n match {
    case x if x < 0 => throw new IllegalArgumentException("Factorial only works for positive integers")
    case 0 => 1
    case _ => 1 to n product
  }
}

Exercise 5: Other Functions

As this exercise required the demonstration of a handful of functions that Clojure already has defined, I was able to use the Scala analogues in most cases:

class OtherFunctionsSpec extends UnitSpec {
  "Exercise 5a: take" should "create a new sequence of the first n elements of an existing sequence" in {
    1 to 10 take 3 should be (List(1, 2, 3))
  }

  "Exercise 5b: distinct" should "remove duplicates from an existing sequence" in {
    val dupes = Seq(1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6)
    dupes.distinct should be (1 to 6)
  }

  "Exercise 5c: ++" should "concatenate two sequences together" in {
    val a = 1 to 3
    val b = 4 to 6
    a ++ b should be (1 to 6)
  }

  "Exercise 5d: fill" should "create a sequence containing n copies of the same value" in {
    Seq.fill(5)(2) should be (Seq(2, 2, 2, 2, 2))
  }

  "Exercise 5e: interleave" should "interleave the elements of two sequences together" in {
    val evens = 0 to 8 by 2
    val odds = 1 to 9 by 2
    evens interleave odds should be (0 to 9)
  }

  "Exercise 5f.i: drop" should "remove the first n items from the sequence" in {
    1 to 10 drop 3 should be (4 to 10)
  }
  "Exercise 5f.ii: dropRight" should "remove the last n items from the sequence" in {
    1 to 10 dropRight 3 should be (1 to 7)
  }

  "Exercise 5g: flatten" should "turn a sequence of sequences into a sequence containing all of the values of each subsequence" in {
    Seq(1 to 3, 4 to 6, 7 to 9).flatten should be (1 to 9)
  }

  "Exercise 5h: grouped" should "yield an iterator that turns the given sequence into a sequence of subsequences, each n items long" in {
    (1 to 9 grouped 3).toSeq should be (Seq(1 to 3, 4 to 6, 7 to 9))
  }

  "Exercise 5i: forall" should "test whether all items in a sequence meet a certain condition" in {
    1 to 9 forall { _ < 10 } should be (true)
  }

  "Exercise 5j: filterNot" should "remove items meeting a certain criterion from a given sequence" in {
    1 to 10 filterNot { _ % 3 == 0 } should be (Seq(1, 2, 4, 5, 7, 8, 10))
  }
}

Nevertheless, Clojure has one function interleave that Scala does not have out of the box, so I had to implement it myself as an extension method:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def interleave(that: Seq[A]): Seq[A] = {
      (seq, that).zipped flatMap { Seq(_, _) }
    }
  }
}

Exercise 6: prefixOf

class PrefixOfSpec extends UnitSpec {
  "Exercise 6: prefixOf" should "test whether a sequence consists of the first few elements of another sequence" in {
    (1 to 3) prefixOf (1 to 10) should be (true)
  }
}

Scala already has startsWith, but it seemed like cheating to use it to implement prefixOf:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def prefixOf(that: Seq[A]): Boolean = {
      that startsWith seq
    }
  }
}

So I used take:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def prefixOf(that: Seq[A]): Boolean = {
      (that take seq.length) == seq
    }
  }
}

Exercise 7: tails

I came up with three implementations.

class TailsSpec extends UnitSpec {
  val seq = 1 to 4
  val expected = Seq(1 to 4, 2 to 4, 3 to 4, 4 to 4, 4 until 4)
  "Exercise 7a: tails1" should "return a sequence of successively smaller subsequences of the argument" in {
    seq.tails1 should be (expected)
  }
}

Scala already has an implementation of tails although it returns an iterator instead of a fully constructed sequence. Implementing the version of Mr. Marick’s tails function was no harder than calling toSeq:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def tails1: Seq[Seq[A]] = seq.tails.toSeq
  }
}

But again, that seems like cheating, so my second implementation was my own.

class TailsSpec extends UnitSpec {
  val seq = 1 to 4
  val expected = Seq(1 to 4, 2 to 4, 3 to 4, 4 to 4, 4 until 4)
  "Exercise 7b: tails2" should "return a sequence of successively smaller subsequences of the argument" in {
    seq.tails2 should be (expected)
  }
}

The solution that first occurred to me was to use pattern matching and recursion:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def tails2: Seq[Seq[A]] = {
      def tailn(s: Seq[A]): Seq[Seq[A]] = s match {
        case Seq() => Seq(s)
        case _ => s +: tailn(s.tail)
      }
      tailn(seq)
    }
  }
}

A perfectly valid implementation, and yet I wanted one more.

class TailsSpec extends UnitSpec {
  val seq = 1 to 4
  val expected = Seq(1 to 4, 2 to 4, 3 to 4, 4 to 4, 4 until 4)
  "Exercise 7c: tails3" should "return a sequence of successively smaller subsequences of the argument" in {
    seq.tails3 should be (expected)
  }
}

I took a peek at Mr. Marick’s Clojure implementation. I wanted to do a Scala version of it:

object Chapter01 {
  implicit class Ops[A](val seq: Seq[A]) extends AnyVal {
    def tails3: Seq[Seq[A]] = {
      val seqs = Seq.fill(seq.length + 1)(seq)
      val nToDrop = 0 to seq.length
      (seqs, nToDrop).zipped map (_ drop _)
    }
  }
}

Well, that’s all for Chapter 1. Look for my take on Chapter 2 to come soon. Chapters 2–5 cover embedding an object-oriented language in Clojure. Because Scala is a hybrid functional–object-oriented language, I didn’t really see the point of doing them in Scala. Therefore the next post will cover chapter 6.

Categories
General

Secret Starbucks Drinks

You know you love all the sugary calories you can get from Starbucks drinks, and here are some secret drinks that the baristas will be happy to make for you if you’ll just give them the recipe:

35 Secret Starbucks Drinks You Didn’t Know You Could Order

15 New Secret Starbucks Drinks for Fall and Winter

Categories
Tech

Types With Units

The Problem

I have been working on an application that displays various types of data, and some of the data may be displayed in more than one unit of measure, according to the user’s preference. The diversity of units is not just on the output side. The application consumes a number of input formats: an angle value may be in degrees or radians; a distance value may be in meters or feet.

To cope with all these differences, we created an abstraction layer that converts the various incoming data formats into a common format. Only when we need to display a value in a certain unit of measurement do we perform the units conversion to the desired format. There was a number of occurrences of magic numbers to convert values from one unit to another:

// C#
//Convert from ft/min to m/s
speed = (u.VerticalSpeed * (1 / (3.28084 * 60))) + "  m/s";

Obviously, poor practice that I had to clean up.

More frequently there were no magic numbers, but named constants:

// C#
altitudeValue = Constants.METERS_TO_FEET * u.Position.Altitude;

An improvement, for sure, but there’s still a problem. The units are implied here by the calculation, but if I run across u.Position.Altitude elsewhere in the program, how do I, as the code maintainer, know that Altitude is in meters?

We could depend on convention: Always use SI units. Distances are meters, speeds are meters per second, and so on. Still, from time to time, someone on the team would forget. In fact, the VerticalSpeed calculation above is wrong: VerticalSpeed is in meters per second, not feet per minute. How can we be sure that no one forgets what the units are?

One convention I employ frequently is to add a suffix to the variable/method that indicates its units:

// C#
speed = u.VerticalSpeedMeters + " m/s";

It works, but can get a little verbose. It becomes necessary to attach a units suffix to every single variable, even when there is no units conversion going on.

Furthermore, every time there is a units conversion, we have to type out the calculation. While simple enough, that’s code duplication. How can we reduce duplication?

I have recently been more scrupulous about encapsulating a frequently performed calculation—even a simple one—within a method named so that it describes the operation. In fact, in doing so, I kill two birds with one stone: reduce code duplication and eliminate the need for a comment because the method name already tells you exactly what it’s doing:

// C#
lat = ConvertRadiansToDegrees(latitudeRadians);

That is better, but it feels a little too C-like. Yeah, it’s a matter of taste, but I don’t like it.

Finally, there’s nothing that prevents me from doing this:

// C#
lat = ConvertRadiansToDegrees(accelerationMeters);

The compiler cannot help me. First, the correct units of acceleration are meters/second², not meters. Second, I am handing an acceleration value to a function that expects an angle value. The compiler does not catch the mismatch because both angles and accelerations are doubles—as are distances, speeds, flow rates, angular speeds, etc. Can we somehow use the type system to enlist the compiler’s help?

The Solution

So then, here are the forces our solution has to balance:

  • Eliminates magic numbers
  • Encapsulates the units conversion algorithm
  • Communicates the units of measure when we care, but does not clutter the code when we don’t
  • Has a less C-like, more OO feel
  • Uses the type system to help prevent accidental mismatches of different measurement types

What if we use custom types for each measurement type rather than a generic double? For example, what if we could do this for angles?

// C#
Angle lat = new Angle(Math.PI / 2.0);
double rad = lat.Radians;
double deg = lat.Degrees;

Well, in fact, we can: using classes—or rather C# structs in our case since that is the C# way for value types.

Let’s take the TDD approach and write our test first.

// C#
namespace UnitsOfMeasureTests.Units
{
    [TestFixture]
    class AngleTest
    {
        private const double OneRadianInRadians = 1.0;
        private const double OneRadianInDegrees = 180.0 / Math.PI;

        private const double OneDegreeInDegrees = 1.0;
        private const double OneDegreeInRadians = Math.PI / 180.0;

        [Test]
        public void TestRadiansProperty()
        {
            Angle angle;

            angle = new Angle(OneRadianInRadians);
            Assert.That(angle.Radians, Is.EqualTo(OneRadianInRadians));
            angle = new Angle(OneDegreeInRadians);
            Assert.That(angle.Radians, Is.EqualTo(OneDegreeInRadians));
        }

        [Test]
        public void TestDegreesProperty()
        {
            Angle angle;

            angle = new Angle(OneRadianInRadians);
            Assert.That(angle.Degrees, Is.EqualTo(OneRadianInDegrees));
            angle = new Angle(OneDegreeInRadians);
            Assert.That(angle.Degrees, Is.EqualTo(OneDegreeInDegrees));
        }
    }
}

Now the implementation:

//C#
namespace UnitsOfMeasure.Units
{
    public struct Angle
    {
        public readonly double Radians;
        public readonly double Degrees;

        private const double DegreesPerRadian = 180.0 / Math.PI;

        public Angle(double radians)
        {
            this.Radians = radians;
            this.Degrees = radians * DegreesPerRadian;
        }
    }
}

That’s not bad, but we can do better. Consider this:

// C#
Angle latitude = new Angle(latValue);

How do I know at a quick glance whether latValue is in radians or degrees? I have no idea unless I look at the constructor to find out what units it expects. To make the the code communicate a little better, let’s employ the named constructor idiom. First, we change our test:

// C#
namespace UnitsOfMeasureTests.Units
{
    [TestFixture]
    class AngleTest
    {
        private const double OneRadianInRadians = 1.0;
        private const double OneRadianInDegrees = 180.0 / Math.PI;

        private const double OneDegreeInDegrees = 1.0;
        private const double OneDegreeInRadians = Math.PI / 180.0;

        [Test]
        public void TestRadiansProperty()
        {
            Angle angle;

            angle = Angle.InRadians(OneRadianInRadians);
            Assert.That(angle.Radians, Is.EqualTo(OneRadianInRadians));
            angle = Angle.InRadians(OneDegreeInRadians);
            Assert.That(angle.Radians, Is.EqualTo(OneDegreeInRadians));

            angle = Angle.InDegrees(OneRadianInDegrees);
            Assert.That(angle.Radians, Is.EqualTo(OneRadianInRadians));
            angle = Angle.InDegrees(OneDegreeInDegrees);
            Assert.That(angle.Radians, Is.EqualTo(OneDegreeInRadians));
        }

        [Test]
        public void TestDegreesProperty()
        {
            Angle angle;

            angle = Angle.InRadians(OneRadianInRadians);
            Assert.That(angle.Degrees, Is.EqualTo(OneRadianInDegrees));
            angle = Angle.InRadians(OneDegreeInRadians);
            Assert.That(angle.Degrees, Is.EqualTo(OneDegreeInDegrees));

            angle = Angle.InDegrees(OneRadianInDegrees);
            Assert.That(angle.Degrees, Is.EqualTo(OneRadianInDegrees));
            angle = Angle.InDegrees(OneDegreeInDegrees);
            Assert.That(angle.Degrees, Is.EqualTo(OneDegreeInDegrees));
        }
    }
}

Then we change our implementation to match by making the constructor private and adding the two named constructors InRadians and InDegrees:

// C#
namespace UnitsOfMeasure.Units
{
    public struct Angle
    {
        public readonly double Radians;
        public readonly double Degrees;

        private const double DegreesPerRadian = 180 / Math.PI;

        public static Angle InRadians(double radians)
        {
            return new Angle(radians);
        }

        public static Angle InDegrees(double degrees)
        {
            return new Angle(degrees / DegreesPerRadian);
        }

        private Angle(double radians)
        {
            Radians = radians;
            Degrees = radians * DegreesPerRadian;
        }
    }
}

Now it is perfectly clear whether we are initializing a new Angle object with a radian value or a degree value.

So there it is. We now have an Angle value type that eliminates magic numbers and code duplication by encapsulating the units conversions within the struct. Instead of being constrained to a primitive double value that could be confused with any other double, we can now lean on the compiler for help. Finally, instead of having to append units suffixes all over the place, we pass around an object that can give us its value in whatever units we desire only when the units matter:

// C#
Angle latitude = Angle.InRadians(message.CurrentPosition.Latitude);
latTextBox.Value = String.Format("{0:0}°", latitude.Degrees);

Case In Point: NASA World Wind

I had already dreamt up my design independently, but I came to find out that NASA’s World Wind has an Angle class that does things similar to how our Angle struct above does. In fact, it has some additional features, such as arithmetic and trigonometric functions, which I should like to add to my Angle type in future posts.