Is a function that calls Math.random() pure?

后端 未结 9 1589
[愿得一人]
[愿得一人] 2021-01-30 15:30

Is the following a pure function?

function test(min,max) {
   return  Math.random() * (max - min) + min;
}

My understanding is that a pure func

9条回答
  •  一生所求
    2021-01-30 15:55

    From mathematical point of view, your signature is not

    test:  -> 
    

    but

    test:  -> 
    

    where the environment is capable of providing results of Math.random(). And actually generating the random value mutates the environment as a side effect, so you also return a new environment, which is not equal to the first one!

    In other words, if you need any kind of input that does not come from initial arguments (the part), then you need to be provided with execution environment (that in this example provides state for Math). The same applies to other things mentioned by other answers, like I/O or such.


    As an analogy, you can also notice this is how object-oriented programming can be represented - if we say, e.g.

    SomeClass something
    T result = something.foo(x, y)
    

    then actually we are using

    foo:  -> 
    

    with the object that has its method invoked being part of the environment. And why the SomeClass part of result? Because something's state could have changed as well!

提交回复
热议问题