Skip to content

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

  1. Try it yourself first — set the solution aside and re-implement from the prompt below.
  2. Run go test ./... from this directory.
  3. 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 numeric Sum[T Number] (union constraint ~int | ~int64 | ~float64), Keys[K,V] (K comparable), and Max[T cmp.Ordered] returning comma-ok. Notice which constraint each operation forces.
  • genstack: Build Stack[T any] with Push, Pop/Peek (comma-ok, returning var zero T on empty), Len, IsEmpty. Prove a zero-value Stack[T]{} is usable and that Pop on empty returns the zero value + false.
  • genset: Build Set[T comparable] with Add/Remove/Contains/Len and set algebra (Union, Intersect, Difference) that returns a NEW set without mutating operands, plus an order-independent Equal.

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 ./....


Exercises