Question

I'm reading about pure-functions in functional programming and am wondering, whether a function being deterministic implies that the function is also side-effect free? (and vice versa?)

Was it helpful?

Solution

Pure = deterministic + without side effects

A function is pure only, if both criteria are met. If it meets only one of them, it's not pure.

Deterministic but with sideeffects:

As pointed out by @Caleth

int DeterministicButSideeffects(int param)
{
    Console.Writeline("Sideeffect"); // Side effect here
    this.someVariable = param; // Another side effect

    return param; // Result only depends on the parameters
}

Without sideeffects but not deterministic

int NonDeterministicWithoutSideeffects(int param)
{
    return param + getRandomIntNumber(); // Result depends on random number
}

Note that side effects are only "outbound". If a function modifies the state of the containing code (global variable or field in a class) or if it performs some I/O-operations, it has side effects.

Another very simple function that is not deterministic would be:

DateTime GetCurrentDateTime()
{
    return DateTime.Now; // -> Result depends on current datetime
}

Pure:

int add(int num1, int num2)
{
    return num1 + num2;
}

OTHER TIPS

It's easy to show that a function being deterministic doesn't imply that it is pure, with a simple counterexample:

int DeterministicButNotPure(int param)
{
    Console.Writeline("Foo invoked"); // Side effect here
    return param; // Result only depends on the parameters
}
Licensed under: CC-BY-SA with attribution
scroll top