✨ ARCANUM RUNE DIFFICULTY: Apprentice Behavioral

The Chain of Responsibility

Pass a request along a chain of magical handlers until one resolves it.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Chain of Responsibility
ARCANUM SCHOOL: Evocation // Invocation Routing
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// CODEX INCANTATION //
structural type SpellRequest = SpellRequest Text

type Handler = SpellRequest -> Optional Text

fireHandler : Handler
fireHandler req = match req with
  SpellRequest "fire" -> Some "Cast Fireball!"
  _ -> None
  
iceHandler : Handler
iceHandler req = match req with
  SpellRequest "ice" -> Some "Cast Ice Storm!"
  _ -> None
  
chain : [Handler] -> SpellRequest -> Optional Text
chain handlers req =
  List.foldLeft (acc h -> match acc with
    Some res -> Some res
    None -> h req
  ) None handlers
  
masterEvoker : SpellRequest -> Optional Text
masterEvoker = chain [fireHandler, iceHandler]

The Chain of Responsibility takes a functional form in Unison. Rather than objects holding references to their successors, we define handlers as simple functions returning an Optional result. The chain itself is a sequence of these functions, folded over the request. The arcane weave traverses the list of handlers until a non-empty result (Some) is discovered, at which point the spell resolves.

Runic Tags: #behavioral #chain-of-responsibility #unison #lists #functional