Skip to content

Instantly share code, notes, and snippets.

@andymatuschak
andymatuschak / States-v3.md
Last active April 12, 2024 16:06
A composable pattern for pure state machines with effects (draft v3)

A composable pattern for pure state machines with effects

State machines are everywhere in interactive systems, but they're rarely defined clearly and explicitly. Given some big blob of code including implicit state machines, which transitions are possible and under what conditions? What effects take place on what transitions?

There are existing design patterns for state machines, but all the patterns I've seen complect side effects with the structure of the state machine itself. Instances of these patterns are difficult to test without mocking, and they end up with more dependencies. Worse, the classic patterns compose poorly: hierarchical state machines are typically not straightforward extensions. The functional programming world has solutions, but they don't transpose neatly enough to be broadly usable in mainstream languages.

Here I present a composable pattern for pure state machiness with effects,

@beccadax
beccadax / BitSet.swift
Last active May 13, 2016 02:57
Minimal BitSet type capable of handling integer-based RawRepresentable enums. Does not implement all of Set's functionality, but the skeleton is here.
// This is basically a polymorphic constant.
// We don't base it on sizeof(IntMax) because that returns Int, which we may not be able to convert to the correct IntegerType.
private func intMaxBitSize<T: IntegerType>() -> T {
return 63
}
public struct BitSet<T: RawRepresentable where T.RawValue: IntegerType>: RawRepresentable {
private(set) public var rawValue: IntMax = 0
public init() {}