Can pure functions read global state?

Please note: with the "pure" function, I do not mean the "pure virtual"
I mean this

If a function reads some global state, does that automatically make it unclean? or does it depend on other factors?

If this automatically makes it unclean, explain why.

If it depends on other factors, please explain what it is.

+3
source share
4 answers

A "pure" function is a function whose result depends only on the input arguments. If he reads anything else, this is not a pure function.

+7
source

. , , , , , , . :

static int cache[256] = {0};
int compute_something(uint8_t input)
{
    if(cache[input] == 0)
        cache[input] = (perform expensive computation on input that won't return 0);
    return cache[input];
}

, cache, , . - - , .

+3

. .

, "" , .

. :

, ( ), . , , , . ( , , ( ) , - , .)

0

In Haskell, for example, you can create an endless list of random numbers on the unclean side and pass this list to your pure function. The implementation will generate the next number that your pure function uses only when it needs it, but the function is still clean.

0
source

Source: https://habr.com/ru/post/1704182/


All Articles