Translating math into code with examples in Java, Racket, Haskell and Python
discrete-mathematicsfunctional-programmingtype-theorycoding-patterns
Abstraction: Mapping discrete math structures to immutable functional code patterns
Key points:
- Mathematics has no side effects; correct code translation must use immutable data structures — mutable structures are a fatal mistake
- Sets map to types, sorted tree-backed collections, or predicates depending on whether membership is static, runtime-computed, or structural
- Disjoint union (sum types) maps to class inheritance in Java or algebraic data types in Haskell
- Sequences map to linked lists; vectors to arrays (never mutated); infinite sequences to lazy streams in Haskell or Racket
- Functions as finite maps should use immutable red-black trees or shallow-copy dict wrappers, not Python dicts or Java TreeMap directly
- Relations can be encoded as collections of tuples, as functions (A → P(B)), or as predicates
Connections: Haskell · Functional Programming · Discrete Mathematics · Type Theory
Source: http://matt.might.net/articles/discrete-math-and-code/