0

A pure function is defined as a function that:

  1. Returns the same value for the same arguments, and
  2. Does not produce any side effects (mutation of non-local variables, I/O operations, etc.)

Consider a function that calculates the greatest common divisor of two positive integers by randomly sampling integers between 1 and the lowest of the two numbers, and determining if the sampled integer divides the two given integers. When all of the integers have been visited, the function returns the highest sampled integer. Assume the random number generator used is uniform.

Intuitively, it seems to me that this function is pure, despite its computation being non-deterministic. It produces the same value for the same arguments, and does not produce any side effects. The only possible "side effect" I can think of is there is the possibility of the computation going on forever, given a large enough input. Am I correct in labeling this function pure?

mario_sunny
  • 1,412
  • 11
  • 29
  • It is only pure if you create a new random generator for the function, seeded by a non-random seed, and discard it afterwards, which makes it effectively non-random. (If you use a random seed, you're affecting an outside randomness source). – Amadan Jul 04 '19 at 23:58
  • 1
    It does meet 1, but it doesn't meet 2 if it uses an external RNG. – Enigmativity Jul 05 '19 at 00:22
  • How does the function know "when all the integers have been visited"? Or does that just remain unspecified? – President James K. Polk Jul 05 '19 at 03:54

2 Answers2

3

No, I don't think so.

As for random number generators, there are two possibilities:

  1. It is a Pseudo-RNG. It means it has an N-bit state, and each time a new random number is generated, the state gets updated. So there is a side effect - a change in the RNG state.

  2. A True random generator, which draws random bits from entropy source. Again, the pool will be drawn upon and might be exhausted - here is a sign of a non-pure function.

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64
1

A "random number generator" can't be a pure function unless all the information it needs to generate a random-looking number is passed to it up front. If the generator uses anything else (such as the system clock or the file system), the generator will not be pure. For example, pure functions include:

  • Hash functions.
  • Functions that take a seed and output a random-looking number and a new seed.
  • Functions that take an internal state and output a random-looking number and a new internal state.

See my section "Designs for PRNGs".

Peter O.
  • 32,158
  • 14
  • 82
  • 96