Table of Contents
Month 1 · Week 4 — Exercises¶
Practice for generics: generic functions over slices/maps and generic data structures. Each folder is its own package with a solution and table-driven tests, using only the standard library.
| Exercise | Concept | Day | Run tests |
|---|---|---|---|
genslice/ |
Map/Filter/Reduce/Sum/Keys/Max, constraints (any, comparable, cmp.Ordered, union ~) |
023 | go test ./genslice |
genstack/ |
generic Stack[T any], comma-ok Pop/Peek, generic zero value |
024 | go test ./genstack |
genset/ |
generic Set[T comparable], Union/Intersect/Difference/Equal |
024 | go test ./genset |
How to use¶
- Try it yourself first — set the solution aside and re-implement from the prompt below.
- Run
go test ./...from this directory. - Compare with the provided solution; log differences in your day note's "Mistakes" section.
Prompts¶
- genslice: Write generic
Map[T,U],Filter[T],Reduce[T,U], a numericSum[T Number](union constraint~int | ~int64 | ~float64),Keys[K,V](Kcomparable), andMax[T cmp.Ordered]returning comma-ok. Notice which constraint each operation forces. - genstack: Build
Stack[T any]withPush,Pop/Peek(comma-ok, returningvar zero Ton empty),Len,IsEmpty. Prove a zero-valueStack[T]{}is usable and thatPopon empty returns the zero value + false. - genset: Build
Set[T comparable]withAdd/Remove/Contains/Lenand set algebra (Union,Intersect,Difference) that returns a NEW set without mutating operands, plus an order-independentEqual.
Results¶
| Exercise | Tests | Status |
|---|---|---|
| genslice | Map, Filter, Reduce, Sum, Keys, Max |
✅ pass |
| genstack | PushPopLIFO, PopEmpty, Peek, ZeroValue, Structs |
✅ pass |
| genset | AddContainsRemove, SetAlgebra, Equal, Structs |
✅ pass |
Tip: run all of Week 4 at once with
go test ./....