7. Functions as values

The restaurant’s owner wants deposits to depend on the night. Fridays and Saturdays should be £15 a head for any party of four or more, and on New Year’s Eve everybody pays £25 a head. At the moment there’s one rule, written into a method on Party with its numbers inside it.

We could add a method for each kind of night and an if to choose between them. I’d make the rule a value instead: a function that we can store in a val, pass to a method and build out of other rules.

7.1. A rule as a value

Create deposits.scala:

package fullybooked

type DepositRule = Party => BigDecimal

def perHead(amount: BigDecimal, from: Int): DepositRule =
  party => if party.size >= from then amount * party.size else BigDecimal(0)

val weekday: DepositRule = perHead(BigDecimal(10), from = 6)
val weekend: DepositRule = perHead(BigDecimal(15), from = 4)
val newYearsEve: DepositRule = perHead(BigDecimal(25), from = 1)

The type line gives the name DepositRule to Party => BigDecimal, the type of any function that takes a Party and returns a BigDecimal. The compiler has been inferring types like that for most of the lambdas we’ve written. It treats the name and the longer spelling as the same type, so the name only saves us from repeating it.

The lambda that perHead returns can still read amount and from long after perHead itself has returned. A function that holds on to values from the place it was written is a closure. So weekday, weekend and newYearsEve are three different functions, each with its own amount and threshold inside it. To use one, write the party in parentheses after it, as in weekday(party).

In Java the type would be Function<Party, BigDecimal> and the call rule.apply(party). Underneath, Scala does much the same: weekday is an object, and weekday(party) runs its apply method.

Delete the deposit method from Party in model.scala, now that the rule lives in deposits.scala. The test called “deposits start at six people” in party.test.scala no longer compiles, so delete that as well. Its replacement goes in a new file, deposits.test.scala:

package fullybooked

import java.time.LocalTime

class DepositTests extends munit.FunSuite:
  val five = Party("Okonkwo", 5)
  val six = Party("Haddad", 6)

  test("weekday deposits start at six people"):
    assertEquals(weekday(five), BigDecimal(0))
    assertEquals(weekday(six), BigDecimal(60))

  test("weekend deposits are higher and start at four"):
    assertEquals(weekend(Party("Moreau", 3)), BigDecimal(0))
    assertEquals(weekend(five), BigDecimal(75))

Run scala test . and all four suites should pass.

7.2. Handing a rule to a method

To add up tonight’s deposits we need to know which rule is in force, so the method that does it takes the rule as a parameter. Add this to the end of deposits.scala:

def depositsDue(bookings: List[Booking], rule: DepositRule): BigDecimal =
  bookings.filter(holdsTable).map(booking => rule(booking.party)).sum

A caller can pass any function from Party to BigDecimal as rule. In Java’s strategy pattern the caller would pass an object of a class that implements an interface. A method like depositsDue that takes a function is called a higher-order function, and so is one that returns a function, as perHead does. Add a test for depositsDue to the end of DepositTests:

  test("deposits are only due from bookings that hold a table"):
    val eight = LocalTime.of(20, 0)
    val bookings = List(
      Booking(six, Table(5, 6), eight, Status.Confirmed),
      Booking(Party("Lindqvist", 7), Table(6, 8), eight, Status.Cancelled)
    )
    assertEquals(depositsDue(bookings, weekday), BigDecimal(60))

To see what each rule charges, add another @main to the end of main.scala:

@main def deposits(): Unit =
  val rules = List("Weekday" -> weekday, "Weekend" -> weekend, "New Year's Eve" -> newYearsEve)
  for (name, rule) <- rules do
    val amounts = List(2, 4, 6, 8).map(size => rule(Party("Example", size)))
    println(s"$name: $amounts, due tonight ${depositsDue(tonight, rule)}")
$ scala run . --main-class fullybooked.deposits
Weekday: List(0, 0, 60, 80), due tonight 70
Weekend: List(0, 60, 90, 120), due tonight 240
New Year's Eve: List(50, 100, 150, 200), due tonight 575

The for takes each pair in the list apart into name and rule.

We’ve been passing methods like holdsTable to filter since chapter 4. Strictly, a method isn’t a value: it belongs to the class, object or file it’s declared in. Those calls work because the compiler turns a method into a function wherever a function is expected, so a rule written as def flatTen(party: Party): BigDecimal could be passed to depositsDue too. I write def by default and use a function value when other code has to build it, as perHead builds these rules.

7.3. Rules made from rules

Bank holidays get the weekend rule or £20 a head for parties of eight and over, whichever is more, up to a limit of £150. We can build that out of the rules we already have. Add these to the end of deposits.scala:

def cappedAt(limit: BigDecimal): BigDecimal => BigDecimal =
  amount => amount.min(limit)

def higherOf(first: DepositRule, second: DepositRule): DepositRule =
  party => first(party).max(second(party))

val bankHoliday: DepositRule =
  higherOf(weekend, perHead(BigDecimal(20), from = 8)).andThen(cappedAt(BigDecimal(150)))

In bankHoliday, higherOf makes one rule from two. andThen hands that rule’s answer to the function cappedAt returned, which lowers the amount to the limit if it’s over. Every one-argument function has an andThen method. The call only compiles if the first function returns what the second takes. There’s a compose as well, which joins two functions in the opposite order, but I stick to andThen because it reads in the order things happen.

Take a party of eight. The weekend rule says £120, the other says £160, the higher is £160 and the cap brings it down to £150. Put that in a test at the end of DepositTests:

  test("a bank holiday takes the higher rule and stops at 150"):
    assertEquals(bankHoliday(five), BigDecimal(75))
    assertEquals(bankHoliday(Party("Castellanos", 8)), BigDecimal(150))

7.4. Longer lambdas

Cancellations have rules as well: someone who cancels on the day gets the whole deposit back with six hours’ notice, half with two, and otherwise nothing. This rule needs two arguments, the deposit and the hours of notice, and a body of several lines. Put import java.time.{Duration, LocalTime} under the package line of deposits.scala, then add this to the end of the file:

type RefundRule = (BigDecimal, Long) => BigDecimal

val sameDay: RefundRule = (deposit, hoursNotice) =>
  if hoursNotice >= 6 then deposit
  else if hoursNotice >= 2 then deposit / 2
  else BigDecimal(0)

def refund(booking: Booking, now: LocalTime, deposit: DepositRule, rule: RefundRule): BigDecimal =
  val notice = Duration.between(now, booking.time).toHours
  rule(deposit(booking.party), notice)

The two arguments of a RefundRule go in parentheses in its type. The hours are a Long because toHours, a method on Java’s Duration, returns one. In sameDay the body starts on the line after the => and is indented, the way a method’s body follows its =. refund then needs both kinds of rule: deposit to work out what was paid and rule to decide how much of it comes back.

The test for refund goes at the end of DepositTests:

  test("a same-day cancellation gets half back with two hours' notice"):
    val booking = Booking(six, Table(5, 6), LocalTime.of(20, 0), Status.Confirmed)
    assertEquals(refund(booking, LocalTime.of(13, 0), weekday, sameDay), BigDecimal(60))
    assertEquals(refund(booking, LocalTime.of(17, 30), weekday, sameDay), BigDecimal(30))
    assertEquals(refund(booking, LocalTime.of(19, 0), weekday, sameDay), BigDecimal(0))

In chapter 5 reserve stayed a match because its second case was too long for a one-line lambda. A lambda with an indented body, like the one in sameDay, is long enough, so the match can become a map. Replace reserve in availability.scala:

def reserve(store: BookingStore, party: Party, time: LocalTime): Option[Booking] =
  bestTable(party, time, store.all).map: table =>
    Thread.sleep(300)
    val booking = Booking(party, table, time, Status.Confirmed)
    store.add(booking)
    booking

The colon after map says that its argument comes next: the lambda’s parameter and => on the same line, then the body on the indented lines beneath. We’ve been writing that colon after test(...) since chapter 6. Code written with braces has .map { table => ... } here, with the closing brace after the last line.

Run the tests: the one in StoreTests that calls reserve should still pass.

7.5. Several parameter lists

A method can declare more than one parameter list. In chapter 4, foldLeft took its arguments in two pairs of parentheses, foldLeft(0)((total, booking) => ...). Its reason goes back to Scala 2, which worked out types one list at a time. A 0 in a list of its own told the compiler that the running total was an Int before it reached the lambda. Scala 3 can usually work that out within a single list, but foldLeft still has two.

The kitchen takes bookings from noon until half past nine, and any code that makes a booking should check that first. A method with two parameter lists can do the check and take the booking code as its second list, written after a colon. Add the hours and the method to the end of availability.scala:

val opens = LocalTime.of(12, 0)
val lastOrders = LocalTime.of(21, 30)

def whenOpen(time: LocalTime)(action: => String): String =
  if time.isBefore(opens) || time.isAfter(lastOrders) then s"The kitchen is closed at $time"
  else action

The type of action is => String, with nothing to the left of the arrow, which makes it a by-name parameter. Scala works out an ordinary argument before it calls the method, but it hands a by-name argument over as code. A Java method would declare a Supplier<String> for this, and its caller would write () -> in front of the code. In Scala the caller writes only the code, and it runs each time the method’s body uses action, or not at all if the body never does.

Add a @main to the end of main.scala to try it:

@main def openingHours(): Unit =
  val store = InMemoryBookingStore()
  val party = Party("Silva", 2)
  for time <- List(LocalTime.of(11, 0), LocalTime.of(20, 0)) do
    val answer = whenOpen(time):
      println(s"Looking for a table at $time")
      reply(party.name, reserve(store, party, time))
    println(answer)
$ scala run . --main-class fullybooked.openingHours
The kitchen is closed at 11:00
Looking for a table at 20:00
Silva: table 1 at 20:00

At eleven the block after whenOpen(time): didn’t run: nothing was printed from inside it and no table was reserved. At eight it ran, with its last line as the value of action. MUnit’s test takes the name in one list and a by-name body in the next, which lets it collect every test in a suite first and run the bodies later.

A method with two lists can be called with only the first. If perHead were def perHead(amount: BigDecimal, from: Int)(party: Party): BigDecimal, then perHead(BigDecimal(15), 4) would be a function that still needs a party, in other words a DepositRule. A method written that way is said to be curried.

7.6. Lambdas made of cases

Each afternoon someone rings round the confirmed bookings to check that the guests are still coming. The list to ring from needs the time, name and number of every confirmed booking that has a phone number. We could build it with a filter and then a map, but collect does both at once. Add this to the end of desk.scala:

def toReconfirm(bookings: List[Booking]): List[String] =
  bookings.collect:
    case Booking(Party(name, _, Some(phone)), _, time, Status.Confirmed) =>
      s"$time $name on $phone"

Add one more @main to the end of main.scala:

@main def reconfirm(): Unit =
  for line <- toReconfirm(tonight) do println(line)
$ scala run . --main-class fullybooked.reconfirm
19:30 Okonkwo on 07700 900141
20:00 Lindqvist on 07700 900152
20:15 Moreau on 07700 900164

The lambda we gave collect is a single case with a pattern like those in a match, though it could have had several. The pattern asks for a confirmed booking with Some(phone) inside its Party. collect skips every booking that doesn’t fit and applies the case to the rest.

A lambda that has an answer for some inputs and not for others is a partial function, and collect is built to take one. Give map the same case and the compiler warns that the match may not be exhaustive, then the program throws a MatchError on the first booking in the list, the Haddads’ cancelled one. In library signatures, including the one for collect, the type is written PartialFunction.

You may also meet case lambdas in older code that takes tuples apart. For chapter 4’s (hour, bookings) => ..., Scala 2 needed { case (hour, bookings) => ... }.

7.7. Exercises

Solutions are in the book’s downloadable code, under ch07/exercises.

  1. Write flat(amount: BigDecimal): DepositRule, a rule that charges every party the same deposit whatever its size, and test it.

  2. Write discounted(rule: DepositRule, percent: Int): DepositRule. A weekend party of eight with 20% off should pay £96.

  3. Write strictest(rules: List[DepositRule]): DepositRule, which charges the highest amount that any rule in the list asks for.

  4. Write depositsDueByFold, a version of depositsDue that uses foldLeft with its lambda after a colon. A lambda with two parameters starts (total, booking) =>.

  5. Write twice(action: => Unit): Unit, which uses action two times. Test it with a block that adds one to a var. Then change the parameter’s type to plain Unit and work out why the test fails.

  6. Write bigAndConfirmed(bookings: List[Booking]): List[String], the names of confirmed parties of four or more, using one collect. A case in a lambda can have an if guard.

  7. label still prints “deposit taken” for any confirmed party of six or more, whatever the night. Give it a DepositRule parameter, so that it says so only when the rule charges that party something, and fix the code that calls it.