← Articles Indie Development · Case Study

Compiling the I Ching with Swift: A Serendipitous Encounter of WebAssembly and Classical Divination

A record of the development journey of compiling the I Ching divination engine to WebAssembly, along with reflections on 'change' along the way.

1. Background

As I write this, a light rain is falling outside my window. I’m staring at the line carton bundle in my terminal, and a sudden absurdity strikes me—a divination practice born three thousand years ago is being compiled into WebAssembly bytecode, about to run in browsers all over the world.

Why Do This

The I Ching (易經) divination logic isn’t complicated—at its core it’s just the random grouping of yarrow stalks and the judgment of yin and yang. However, most online hexagram tools on the market are either purely front‑end pseudo‑random or back‑end black boxes. I wanted to build a fully transparent, auditable, locally run divination tool.

WebAssembly is the most suitable choice. It brings Swift’s strong type safety and computational precision to the browser, while ensuring all calculations run locally on the user’s device—no network requests needed.

The Core Challenge: The Mathematical Expression of Yin and Yang

The I Ching’s yin and yang lines have four states:

StateValueMeaning
Old Yang9Extreme yang gives rise to yin; changing line
Young Yang7Yang line; non‑changing
Old Yin6Extreme yin gives rise to yang; changing line
Young Yin8Yin line; non‑changing

The key to the yarrow stalk method (蓍草法) lies in three grouping operations, and the remainder from each operation determines the line’s state. This logic is very clean to implement in Swift:

func yarrowStalkOperation(_ stalks: UInt32) -> UInt32 {
    let left = stalks / 2
    let right = stalks - left
    let remainderLeft = left % 4 == 0 ? 4 : left % 4
    let remainderRight = right % 4 == 0 ? 4 : right % 4
    return remainderLeft + remainderRight + 1
}

The sum of the three operations yields one of 6, 7, 8, or 9, corresponding to the four line states.

On “Change”

While debugging this code, I kept circling back to a question: the core of the I Ching is “change” (變), while the core of programming is determinism.

These two are not contradictory. The randomness of the yarrow stalk method comes from the initial random grouping, while the calculation process itself is completely deterministic. It’s like quantum mechanics—before measurement, a superposition; after measurement, a collapse to a definite value.

Perhaps this is the ancient wisdom: acknowledge the existence of randomness, but seek patterns after the randomness.


The tool is now live—you can try it out at the “Zhouyi Divination (周易起卦)” entry above. If you’re interested in the implementation details, feel free to follow along.