liveBook · Manning

Determinism

As explained in Functional Design and Architecture: Examples in Haskell

Determinism is the property that the same inputs and conditions produce a predictable, uniquely determined result.

Determinism means that the same inputs under the same conditions produce the same result. It makes code easier to reason about, particularly when testing or working with concurrency. section 1.5.1 section 15.1

A pure function produces its result from its arguments without side effects or mutation. Calling it with the same arguments yields the same result, and composing pure functions preserves purity. By contrast, shared mutable state can make a result depend on the order of operations. section 1.5.1 section 15.1.1

def max(a: Float, b: Float) : Float = {
 math.max(a, b)
}
  
def calc(a: Int, b: Int, c: Float) : Float = {
 val sum = a + b
 val average = sum / 2
 max(average, c)
}

The calc function combines an average with max. Because its component functions are pure, the same arguments yield the same result on every call. section 1.5.1

Deterministic code supports repeatable tests, but passing tests cannot rule out every production problem. For code with effects, isolate tests and control shared state so that one test does not depend on another or on their execution order. section 15.1 section 15.1.1

Listing 15.2 Arrange, act, and assert
impureAction :: IORef Int -> (Int -> Int) -> IO Int
impureAction ref f = do
   val <- readIORef ref
   pure (f val)
  
spec :: Spec
spec = do
  describe "IORef tests" $ do
    ref <- newIORef 0
  
    it "test 1" $ do
      writeIORef ref 10                      #1
      result <- impureAction ref (*10)       #2
      result `shouldBe` 100                  #3
  
    it "test 2" $ do
      writeIORef ref 5
      result <- impureAction ref (+10)
      result `shouldBe` 15

Both tests write to the same IORef. If they run in parallel, either write may occur before a read, producing a race and potentially failing assertions. section 15.1.1

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Explains pure-function composition and contrasts it with shared-state races in parallel tests.
Examples
Illustrates pure calculation with an average and maximum, and a race between tests sharing an IORef.
What you can do after
Apply it to testing by isolating effects and avoiding dependencies between tests.
How it connects
Connects pure functions, immutability, shared state, concurrency, and test isolation.

Also explained in

Compare how 10 books explain determinism →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.