Nanyx
PlaygroundPackages

Corner shop

Orders checked with proc, receipts, a stock report and an RPN calculator, all runnable today.

module main

-- A small corner shop, end to end: a catalogue, orders read from text and checked with `proc`,
-- a printed receipt, a stock report with a bar chart, an RPN calculator for the till, and a few
-- statistics about the day. Everything here runs on the current compiler (`nanyx run shop.nyx`).

import (
  nanyx/math as math
  nanyx/text
)

-- Money ------------------------------------------------------------------------------------------

-- Prices are whole pence, so no rounding ever creeps in.
def money: int -> string = { pence ->
  def pounds = pence / 100
  def rest = pence % 100
  "£{pounds}." ++ string.padStart("{rest}", width = 2, fill = "0")
}

-- `text` in a column `width` bytes wide, on the left or the right.
def left: string, int -> string = { text, width ->
  string.padEnd(text, width = width, fill = " ")
}

def right: string, int -> string = { text, width ->
  string.padStart(text, width = width, fill = " ")
}

def rule: int -> string = { width ->
  string.repeat("-", width)
}

-- The catalogue ----------------------------------------------------------------------------------

type Product = (
  sku: string
  name: string
  price: int
  stock: int
)

def catalogue: list(Product) = [
  Product(sku = "TEA", name = "Breakfast tea", price = 289, stock = 14)
  Product(sku = "MLK", name = "Semi-skimmed milk", price = 125, stock = 30)
  Product(sku = "BRD", name = "Sourdough loaf", price = 350, stock = 6)
  Product(sku = "JAM", name = "Raspberry jam", price = 215, stock = 9)
  Product(sku = "EGG", name = "Free-range eggs", price = 310, stock = 12)
  Product(sku = "CHS", name = "Mature cheddar", price = 425, stock = 4)
]

-- The product with code `sku`.
def findProduct: list(Product), string -> #some(Product) | #unknownSku(string) = { products, sku ->
  match products
    | [] -> #unknownSku(sku)
    | [p, ...rest] -> if p.sku == sku then #some(p) else findProduct(rest, sku)
}

-- Reading orders ---------------------------------------------------------------------------------

-- One line of an order: so many of one product.
type OrderLine = (sku: string, qty: int)

-- An order line written as `SKU x QTY`, such as `TEA x 2`.
def parseLine: string -> #some(OrderLine) | #badLine(string) | #badQuantity(string) = { text ->
  match string.words(text)
    | [sku, "x", qty] -> parseQuantity(text, sku, qty)
    | _ -> #badLine(text)
}

def parseQuantity = { text, sku, qty ->
  match int.fromString(qty)
    | #some(n) -> (if n > 0
      then #some(OrderLine(sku = string.uppercase(sku), qty = n))
      else #badQuantity(text))
    | #invalidInt -> #badQuantity(text)
}

-- A line of a checked order: the product, how many, and what they cost together.
type Priced = (
  name: string
  qty: int
  each: int
  cost: int
)

-- `line` priced from `products`, as long as the product exists and there is enough of it.
def priceLine
  : list(Product), OrderLine -> #some(Priced) | #unknownSku(string) | #outOfStock(string)
  = { products, line ->
    match findProduct(products, line.sku)
      | #unknownSku(sku) -> #unknownSku(sku)
      | #some(p) ->
        if line.qty > p.stock
          then #outOfStock(p.name)
          else #some(
            Priced(name = p.name, qty = line.qty, each = p.price, cost = p.price * line.qty)
          )
  }

-- Every line of an order read and priced. The first line that fails stops the order.
def checkOrder = { products, lines -> proc {
    match lines
      | [] -> (return [])
      | [first, ...rest] ->
        def line = try parseLine(first)
        def priced = try priceLine(products, line)
        def others = try checkOrder(products, rest)
        return [priced, ...others]
  }
}

-- Why an order was turned away, in words.
def explain = {
  | #badLine(text) -> "could not read '" ++ text ++ "' (write lines as SKU x QTY)"
  | #badQuantity(text) -> "the quantity in '" ++ text ++ "' is not a positive number"
  | #unknownSku(sku) -> "there is no product " ++ sku
  | #outOfStock(name) -> "not enough " ++ name ++ " in stock"
  | _ -> "something went wrong"
}

-- Receipts ---------------------------------------------------------------------------------------

def subtotal: list(Priced) -> int = {
  | [] -> 0
  | [line, ...rest] -> line.cost + subtotal(rest)
}

def itemCount: list(Priced) -> int = {
  | [] -> 0
  | [line, ...rest] -> line.qty + itemCount(rest)
}

-- A tenth off orders of ten items or more, never more than £5.
def discount: list(Priced) -> int = { lines ->
  if itemCount(lines) >= 10 then math.min(subtotal(lines) / 10, 500) else 0
}

def printLines: [Console] list(Priced) -> () = {
  | [] -> ()
  | [line, ...rest] ->
    println(
      left(line.name, 20) ++ right("{line.qty}", 4) ++ " x " ++ right(money(line.each), 7) ++
        right(money(line.cost), 9)
    )

    printLines(rest)
}

def printReceipt: [Console] string, list(Priced) -> () = { customer, lines ->
  def off = discount(lines)
  println("Receipt for " ++ customer)
  println(rule(43))
  printLines(lines)
  println(rule(43))
  println(left("Subtotal", 34) ++ right(money(subtotal(lines)), 9))
  if off > 0 then println(left("Bulk discount", 34) ++ right("-" ++ money(off), 9))
  println(left("Total ({itemCount(lines)} items)", 34) ++ right(money(subtotal(lines) - off), 9))
  println("")
}

-- Takes one order, one line per item, and prints its receipt or why it was refused.
def takeOrder: [Console] string, list(string) -> () = { customer, order ->
  match checkOrder(catalogue, order)
    | #some(lines) -> printReceipt(customer, lines)
    | failure ->
      println("Order for " ++ customer ++ " refused: " ++ explain(failure))
}

-- Stock report -----------------------------------------------------------------------------------

def bar: int -> string = { n ->
  string.repeat("#", n)
}

def lowStock: list(Product) -> list(Product) = {
  | [] -> []
  | [p, ...rest] -> if p.stock < 8 then [p, ...lowStock(rest)] else lowStock(rest)
}

def reorderFlag: int -> string = { stock ->
  if stock < 8 then "  <- reorder" else ""
}

def printStock: [Console] list(Product) -> () = {
  | [] -> ()
  | [p, ...rest] ->
    println(left(p.sku, 5) ++ right("{p.stock}", 3) ++ " " ++ bar(p.stock) ++ reorderFlag(p.stock))
    printStock(rest)
}

def stockValue: list(Product) -> int = {
  | [] -> 0
  | [p, ...rest] -> p.price * p.stock + stockValue(rest)
}

def names: list(Product) -> list(string) = {
  | [] -> []
  | [p, ...rest] -> [p.name, ...names(rest)]
}

-- The till's calculator --------------------------------------------------------------------------
--
-- Reverse Polish notation: `3 4 + 2 *` is (3 + 4) * 2. Numbers go on a stack; each operator takes
-- the top two off and puts the answer back.

-- Why a calculation failed, or its answer.
type Calc(a) = #some(a) | #divideByZero | #unknownToken(string) | #stackUnderflow(string)

def applyOp: string, int, int -> Calc(int) = { op, a, b ->
  match op
    | "+" -> #some(a + b)
    | "-" -> #some(a - b)
    | "*" -> #some(a * b)
    | "/" -> (if b == 0 then #divideByZero else #some(a / b))
    | "%" -> (if b == 0 then #divideByZero else #some(a % b))
    | "max" -> #some(math.max(a, b))
    | "min" -> #some(math.min(a, b))
    | other -> #unknownToken(other)
}

def isOperator: string -> bool = { token ->
  match token
    | "+" | "-" | "*" | "/" | "%" | "max" | "min" -> true
    | _ -> false
}

-- The stack after one more token.
def push: list(int), string -> Calc(list(int)) = { stack, token ->
  match int.fromString(token)
    | #some(n) -> #some([n, ...stack])
    | #invalidInt -> #unknownToken(token)
}

def operate: list(int), string -> Calc(list(int)) = { stack, token ->
  match stack
    | [b, a, ...rest] -> mapSome(applyOp(token, a, b), { n -> [n, ...rest] })
    | _ -> #stackUnderflow(token)
}

def step: list(int), string -> Calc(list(int)) = { stack, token ->
  if isOperator(token) then operate(stack, token) else push(stack, token)
}

def run: list(int), list(string) -> Calc(list(int)) = { stack, tokens ->
  proc {
    match tokens
      | [] -> (return stack)
      | [token, ...rest] ->
        def next = try step(stack, token)
        return try run(next, rest)
  }
}

def describe: Calc(list(int)) -> string = {
  | #some([n]) -> "= {n}"
  | #some([]) -> "nothing to calculate"
  | #some(_) -> "too many numbers left over"
  | #stackUnderflow(op) -> "not enough numbers for " ++ op
  | #divideByZero -> "cannot divide by zero"
  | #unknownToken(t) -> "do not know '" ++ t ++ "'"
}

def calculate: [Console] string -> () = { program ->
  println(left(program, 22) ++ describe(run([], string.words(program))))
}

-- Statistics -------------------------------------------------------------------------------------

def sum: list(int) -> int = { xs ->
  list.fold(xs, 0, { a, b -> a + b })
}

def largest: list(int) -> int = { xs ->
  list.fold(xs, 0, { a, b -> math.max(a, b) })
}

-- `x` put into the sorted list `xs` where it belongs.
def insert: int, list(int) -> list(int) = { x, xs ->
  match xs
    | [] -> [x]
    | [y, ...rest] -> if x <= y then [x, y, ...rest] else [y, ...insert(x, rest)]
}

def sort: list(int) -> list(int) = { xs ->
  list.fold(xs, [], { sorted, x -> insert(x, sorted) })
}

def median: list(int) -> int = { xs ->
  def sorted = sort(xs)
  def n = list.length(sorted)
  def middle = list.head(list.skip(sorted, n / 2))

  match middle
    | #some(m) -> m
    | #emptyList -> 0
}

def showInt: int -> string = { n ->
  "{n}"
}

def showInts: list(int) -> string = { xs ->
  string.join(list.map(xs, showInt), ", ")
}

-- Hourly takings in whole pounds, from opening at 8 until closing at 6.
def takings = [12, 30, 41, 25, 18, 52, 47, 22, 15, 33]

def printHours: [Console] int, list(int) -> () = { hour, amounts ->
  match amounts
    | [] -> ()
    | [amount, ...rest] ->
      println(right("{hour}:00", 6) ++ " " ++ right("£{amount}", 4) ++ " " ++ bar(amount / 3))
      printHours(hour + 1, rest)
}

def busiest: int, int, int, list(int) -> int = { hour, bestHour, best, amounts ->
  match amounts
    | [] -> bestHour
    | [amount, ...rest] ->
      if amount > best
        then busiest(hour + 1, hour, amount, rest)
        else busiest(hour + 1, bestHour, best, rest)
}

-- Section headings, through a context --------------------------------------------------------------

context Log = (log: [Console] string -> ())

def heading: [Log, Console] string -> () = { title ->
  log("== " ++ string.uppercase(title) ++ " ==")
}

-- The program ------------------------------------------------------------------------------------

@entry
def main = {
  use Log(
    log = { message ->
      println("")
      println(message)
    }
  )

  heading("Orders")
  println("")
  takeOrder("Ada", ["TEA x 2", "mlk x 1", "BRD x 1"])
  takeOrder("Grace", ["EGG x 6", "JAM x 2", "MLK x 4"])
  takeOrder("Alan", ["TEA x 1", "COF x 2"])
  takeOrder("Edsger", ["CHS x 10"])
  takeOrder("Barbara", ["BRD x 1", "BRD two"])

  heading("Stock")
  printStock(catalogue)
  println("Stock value: " ++ money(stockValue(catalogue)))
  println("Running low: " ++ string.join(names(lowStock(catalogue)), ", "))

  heading("Till calculator")
  calculate("3 4 + 2 *")
  calculate("289 2 * 125 +")
  calculate("100 7 %")
  calculate("12 30 max 5 min")
  calculate("5 0 /")
  calculate("1 +")
  calculate("2 3 4 +")
  calculate("2 two *")

  heading("Takings")
  printHours(8, takings)
  println("Total:   £{sum(takings)}")
  println("Best:    £{largest(takings)} at {busiest(8, 8, 0, takings)}:00")
  println("Median:  £{median(takings)}")
  println("Sorted:  " ++ showInts(sort(takings)))
  def quiet = list.filter(takings, { n -> n < 20 })
  println("Quiet hours: {list.length(quiet)} (" ++ showInts(quiet) ++ ")")
}

This program lives in the repository as examples/shop.nyx.