Home / Learn / 10 Collections

Release v0.4.0Edition 0.2

10.9 Exercises

Page 10 of 11

The exercises come with the chapter's download, 10-collections.tar.gz. Each starts from exercises/N/start: a program of this chapter with the exercise's example added, and a stub of the function to write, a header with a placeholder body. The first three start from the day-to-day program, and the last two from the shipping report of A promotion that cannot overcharge. una test . fails there until the exercise is done. Run una fmt . before una check .: canonical form, for example, puts a body of one expression on the header line.

10.9.1 Exercise 1: the SKUs of a category

Write skus_in(lines, category), the SKUs sold in one category, each once, in SKU order. The start package ends with:

exercises/1/start/src/report.unauna
--- The SKUs sold in `category`, each once, in SKU order.
pub skus_in(lines: List[Line], category: Text) -> List[Text] = []

example "each SKU of a category appears once"
  do skus_in(read_all(sample_export()), category: "lighting")
  expect result == ["LAMP-01", "SHADE-05"]

example "a category that sold nothing has no SKUs"
  do skus_in(read_all(sample_export()), category: "garden")
  expect result == []

Hint: a map holds each key once and lists its keys in order, which is exactly "each once, in SKU order". Work in two steps. First keep only the lines of the category, with filter and a lambda that compares line.category with category (section 10.3). Then build a map keyed by SKU from those lines: the program already has a function that does, units_by_sku, and keys() lists its keys (section 10.4). The function's long form, with = on its own line, gives you room for a let.

Check your answer with una test .. On the start package it reports:

Output
example report "each SKU of a category appears once" ... FAILED
  src/report.una:183: expect result == ["LAMP-01", "SHADE-05"]
  it is false, with `result` = `[]`
example report "a category that sold nothing has no SKUs" ... ok

10 examples: 9 passed, 1 failed
Answer (check, run, test; exercises/1/answer).

Give skus_in its body:

src/report.unadiff
--- a/src/report.una
+++ b/src/report.una
@@ -178,3 +178,6 @@
 --- The SKUs sold in `category`, each once, in SKU order.
-pub skus_in(lines: List[Line], category: Text) -> List[Text] = []
+pub skus_in(lines: List[Line], category: Text) -> List[Text]
+=
+  let matching = lines.filter(keep: fn(line) -> line.category == category)
+  units_by_sku(matching).keys()
 

filter keeps the lines of the category, and units_by_sku(matching).keys() gives their SKUs once each, in order.

10.9.2 Exercise 2: say which lines were skipped

The report says how many lines it skipped. Write skipped_lines(export), the numbers of those lines in the export, counting from 1, and print them on the first line of the report: 8 lines, 1 skipped: [5]. The start package ends with:

exercises/2/start/src/report.unauna
--- The numbers of the lines that could not be read, counting from 1.
pub skipped_lines(export: List[Text]) -> List[Int] = []

example "the skipped lines are numbered from 1"
  do skipped_lines(["LAMP-01", "\{\"sku\": \"RUG-07\", \"quantity\": 1, \"cents\": 4500\}", "\{\}"])
  expect result == [1, 3]

Hint: a for loop over the export (section 10.1) with two let edit names declared before it: number, which counts the lines, and numbers, which collects the numbers of the bad ones. At each turn, add 1 to number first, so the first line is 1. Then call read_line on the text, and when its result is None, append number to numbers: found is None is a condition an if can test (section 7.1). Last, change the first print of main to show the list.

Check your answer with una test ., then una run . for the new first line.

Answer (check, run, test; exercises/2/answer).

Give skipped_lines its body, and print its result in main:

src/report.unadiff
--- a/src/report.una
+++ b/src/report.una
@@ -138,3 +138,3 @@
   let skipped = export.len - lines.len
-  @console.print("{export.len} lines, {skipped} skipped")
+  @console.print("{export.len} lines, {skipped} skipped: {skipped_lines(export)}")
   let summaries = by_category(lines).values()
@@ -178,3 +178,12 @@
 --- The numbers of the lines that could not be read, counting from 1.
-pub skipped_lines(export: List[Text]) -> List[Int] = []
+pub skipped_lines(export: List[Text]) -> List[Int]
+=
+  let edit numbers: List[Int] = []
+  let edit number = 0
+  for text in export
+    number = number + 1
+    let found = read_line(text)
+    if found is None
+      numbers = numbers.append(item: number)
+  numbers
 

The example covers a line that is not JSON and an object without a SKU, around a line that is read.

10.9.3 Exercise 3: categories by revenue

Write ranked(summaries), the categories from the highest revenue to the lowest, and print them after the category lines: by revenue: furniture, textiles, lighting, other. When two categories have the same revenue, they keep the order of summaries. The start package ends with:

exercises/3/start/src/report.unauna
--- The categories, the highest revenue first. On a tie they keep the order of `summaries`,
--- which is name order when they come from `by_category`.
pub ranked(summaries: List[Summary]) -> List[Text] = []

example "categories with the same revenue keep the order of the summaries"
  do ranked([Summary(category: "lighting", units: 1, cents: 500), Summary(category: "garden", units: 2, cents: 900), Summary(category: "textiles", units: 5, cents: 500)])
  expect result == ["garden", "lighting", "textiles"]

Hint: sort cannot sort a Summary, and the prelude has no function to sort by a field or to reverse a list. A map lists its keys in ascending order, so let a map do the sorting. Key it by the revenue with its sign changed, -summary.cents, so that the largest revenue becomes the smallest key and comes first. Two categories can have the same revenue, so the value under each key is a list of names: Map[Int, List[Text]], filled with the grouping pattern of Stock by SKU, with [] as the default. Then walk values() and append every name of every list to one result list, with a loop inside a loop.

Check your answer with una test ., then una run . for the new line.

Answer (check, run, test; exercises/3/answer).

Give ranked its body, and print its result in main:

src/report.unadiff
--- a/src/report.una
+++ b/src/report.una
@@ -142,2 +142,4 @@
     @console.print("{summary.category}: {summary.units} units, {money(summary.cents)}")
+  let order = ranked(summaries).join(separator: ", ")
+  @console.print("by revenue: {order}")
   @console.print(headline(best_seller(units_by_sku(lines))))
@@ -179,3 +181,14 @@
 --- which is name order when they come from `by_category`.
-pub ranked(summaries: List[Summary]) -> List[Text] = []
+pub ranked(summaries: List[Summary]) -> List[Text]
+=
+  let edit by_revenue: Map[Int, List[Text]] = empty_map()
+  for summary in summaries
+    let key = -summary.cents
+    let before = by_revenue.get(key: key).or_else(default: [])
+    edit by_revenue.set(key: key, value: before.append(item: summary.category))
+  let edit names: List[Text] = []
+  for group in by_revenue.values()
+    for name in group
+      names = names.append(item: name)
+  names
 

-summary.cents turns the largest revenue into the smallest key, so it comes first. main joins the names with let before printing them, since a text literal such as ", " cannot appear inside an interpolation. Names with the same key are appended in the order of summaries, which by_category gives in name order, and the example with two categories at 500 cents checks it.

10.9.4 Exercise 4: a promotion for members

Members pay 300 cents less for shipping. Write member_discount(charge), and print a sixth line of the shipping report, for order 1047, with the charge of order 1044 at the members' price. The start package ends with:

exercises/4/start/src/shipping.unauna
--- A promotion for members: 300 cents off the charge.
pub member_discount(charge: Int) -> Int = charge

example "members pay 300 cents less"
  do promoted(3_090, promotion: member_discount)
  expect result == 2_790

example "a member never pays less than nothing"
  do promoted(200, promotion: member_discount)
  expect result == 0

Hint: a promotion is a function from a charge to a charge, like half_off, so its body is one line. It only subtracts: promoted already keeps the result between 0 and the charge, so the second example passes once the first does. For the report line, copy the two lines of order 1045 in main and change what they pass.

Check your answer with una test ., then una run . for the new line, order 1047: 27.90.

Answer (check, run, test; exercises/4/answer).

Give member_discount its body, and print order 1047 in main:

src/shipping.unadiff
--- a/src/shipping.una
+++ b/src/shipping.una
@@ -76,2 +76,4 @@
   show(1046, charge: members)
+  let member = promoted(charge, promotion: member_discount)
+  show(1047, charge: member)
 
@@ -114,3 +116,3 @@
 --- A promotion for members: 300 cents off the charge.
-pub member_discount(charge: Int) -> Int = charge
+pub member_discount(charge: Int) -> Int = charge - 300
 

member_discount may give back a negative number for a small charge, and that is fine: the promise not to charge less than nothing belongs to promoted, which every promotion goes through.

10.9.5 Exercise 5: two promotions in a row

Write both(first, second), which gives back a new promotion: first, then second on what first gives. The start package ends with:

exercises/5/start/src/shipping.unauna
--- A promotion made of two: `first`, then `second` on what `first` gives.
pub both(first: fn(Int) -> Int, second: fn(Int) -> Int) -> fn(Int) -> Int = first

example "half off twice is a quarter, rounded up each time"
  do promoted(3_090, promotion: both(half_off, second: half_off))
  expect result == 773

example "the second promotion applies to what the first gives"
  do both(half_off, second: fn(cents) -> cents - 300)(3_090)
  expect result == 1_245

Hint: the result type is fn(Int) -> Int, so the body is a lambda, as in percent_off of section 10.2. The lambda takes a charge, gives it to first, and gives what first returns to second. It may call first and second, which it captures.

Check your answer with una test ..

Answer (check, run, test; exercises/5/answer).

Give back a lambda that applies both:

src/shipping.unadiff
--- a/src/shipping.una
+++ b/src/shipping.una
@@ -114,3 +114,3 @@
 --- A promotion made of two: `first`, then `second` on what `first` gives.
-pub both(first: fn(Int) -> Int, second: fn(Int) -> Int) -> fn(Int) -> Int = first
+pub both(first: fn(Int) -> Int, second: fn(Int) -> Int) -> fn(Int) -> Int = fn(charge) -> second(first(charge))
 

both(half_off, second: half_off) is itself a promotion, so promoted accepts it like any other. The second example calls the returned function at once, both(…)(3_090): 3090 halved is 1545, less 300 is 1245.

Next:10.10 Recap and reference