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









