awelgorithms

Compute a value from the previous

Updated

Some puts are functions of the old value: v = f(old). Missing old needs a seed (0, [], identity). This is fold-per-key.

What to focus on

Do not read a stale copy, mutate it, and forget to put it back if the value is a mutable list you already stored by reference. Know whether get returned a live object.

Worked examples

running max

m = {}, k = 0, x = [4, 1, 9]
  1. max(4,1)=4 then max(4,9)=9

Result: k = 0 → 9

count

m = {}, k = 1, x = [1, 1, 1]
  1. 0+1+1+1

Result: {1:3}

empty seed

a = [1, 1, 1], m = {}, k = 4, x = 1
  1. seed 0 → 1

Result: {4:1}

Try it

Write fold(m, k, x). m is the map. k is the key. x is the next value (or a short stream to fold). A missing key seeds at 0. Put k → f(old, x). Do not drop an old list. m = {}, k = 0, x = [4, 1, 9] → k = 0 → 9. m = {}, k = 1, x = [1, 1, 1] → {1:3}. m = {}, k = 4, x = 1 → {4:1}.

keys are integers. A missing key seeds at 0.