Pure Functions: Does “No Side Effects” Imply “Always Same Output, Given Same Input”?2019 Community...

What happened to QGIS 2.x

Erro: incompatible type for argument 1 of 'printf'

Plagiarism of code by other PhD student

Six real numbers so that product of any five is the sixth one

How to kill a localhost:8080

What are all the squawk codes?

Reason why dimensional travelling would be restricted

Borrowing Characters

If nine coins are tossed, what is the probability that the number of heads is even?

If a set is open, does that imply that it has no boundary points?

Is there a math equivalent to the conditional ternary operator?

Can two networks with the same subnet be connected to the same router in different VRF?

Why do phishing e-mails use faked e-mail addresses instead of the real one?

How do ISS astronauts "get their stripes"?

Pure Functions: Does "No Side Effects" Imply "Always Same Output, Given Same Input"?

Why do members of Congress in committee hearings ask witnesses the same question multiple times?

Can we carry rice to Japan?

Is it possible to convert a suspension fork to rigid by drilling it?

How to mitigate "bandwagon attacking" from players?

I encountered my boss during an on-site interview at another company. Should I bring it up when seeing him next time?

Is divide-by-zero a security vulnerability?

The need of reserving one's ability in job interviews

Canadian citizen, on US no-fly list. What can I do in order to be allowed on flights which go through US airspace?

RS232 to Raspberry Pi Zero W



Pure Functions: Does “No Side Effects” Imply “Always Same Output, Given Same Input”?



2019 Community Moderator ElectionHow to check for an undefined or null variable in JavaScript?Large-scale design in Haskell?How can a time function exist in functional programming?Why are “pure” functions called “pure”?Is Safari on iOS 6 caching $.ajax results?Moment js date time comparisonIs a nested pure function still a pure function?Can a function which returns a new object be considered “pure”?Can a pure function change input arguments?What is the philosophy behind “functional programming” when you actually want to create a side effect?












32















The two conditions that define a function as pure are as follows:




  1. No side effects (i.e. only changes to local scope are allowed)

  2. Always return the same output, given the same input


If the first condition is always true, are there any times the second condition is not true?



I.e. is it really only necessary with the first condition?










share|improve this question




















  • 2





    Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

    – Alexander
    16 hours ago











  • @Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

    – sleske
    12 hours ago






  • 1





    Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

    – Peter A. Schneider
    4 hours ago













  • You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

    – Eric Lippert
    4 hours ago






  • 1





    @EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

    – Peter A. Schneider
    3 hours ago


















32















The two conditions that define a function as pure are as follows:




  1. No side effects (i.e. only changes to local scope are allowed)

  2. Always return the same output, given the same input


If the first condition is always true, are there any times the second condition is not true?



I.e. is it really only necessary with the first condition?










share|improve this question




















  • 2





    Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

    – Alexander
    16 hours ago











  • @Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

    – sleske
    12 hours ago






  • 1





    Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

    – Peter A. Schneider
    4 hours ago













  • You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

    – Eric Lippert
    4 hours ago






  • 1





    @EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

    – Peter A. Schneider
    3 hours ago
















32












32








32


4






The two conditions that define a function as pure are as follows:




  1. No side effects (i.e. only changes to local scope are allowed)

  2. Always return the same output, given the same input


If the first condition is always true, are there any times the second condition is not true?



I.e. is it really only necessary with the first condition?










share|improve this question
















The two conditions that define a function as pure are as follows:




  1. No side effects (i.e. only changes to local scope are allowed)

  2. Always return the same output, given the same input


If the first condition is always true, are there any times the second condition is not true?



I.e. is it really only necessary with the first condition?







javascript functional-programming language-lawyer pure-function






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 11 hours ago









Will Ness

46.1k468126




46.1k468126










asked 22 hours ago









MagnusMagnus

1,52211227




1,52211227








  • 2





    Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

    – Alexander
    16 hours ago











  • @Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

    – sleske
    12 hours ago






  • 1





    Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

    – Peter A. Schneider
    4 hours ago













  • You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

    – Eric Lippert
    4 hours ago






  • 1





    @EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

    – Peter A. Schneider
    3 hours ago
















  • 2





    Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

    – Alexander
    16 hours ago











  • @Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

    – sleske
    12 hours ago






  • 1





    Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

    – Peter A. Schneider
    4 hours ago













  • You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

    – Eric Lippert
    4 hours ago






  • 1





    @EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

    – Peter A. Schneider
    3 hours ago










2




2





Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

– Alexander
16 hours ago





Your premises are ill-specified. "Input" is too broad. Functions can be thought two have kinds of input. Their arguments, and "environmental"/"contextual". A function that returns the system time could be thought to be pure (even though it's obv not) if you don't distinguish between these two kinds of input.

– Alexander
16 hours ago













@Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

– sleske
12 hours ago





@Alexander: In the context of "pure function", "input" is commonly understood to mean the parameters / arguments that are passed explicitly (by whatever mechanism the programming language uses). That's part of the definition of "pure function". But you are right, it's important to mind the definition.

– sleske
12 hours ago




1




1





Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

– Peter A. Schneider
4 hours ago







Trivial counter-example: return the value of a global variable. No side effects (the global is only ever read!), but still potentially different results every time. (If you don't like globals, return the address of a local variable which depends on the call stack at run time).

– Peter A. Schneider
4 hours ago















You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

– Eric Lippert
4 hours ago





You need to expand your definition of "side effects"; you say that a pure method does not produce side effects, but you need to also note that a pure method does not consume side effects produced elsewhere.

– Eric Lippert
4 hours ago




1




1





@EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

– Peter A. Schneider
3 hours ago







@EricLippert OP is simply quoting e.g. wikipedia's criteria. (I'm tempted to call a function communicating through side channels a "leaky gut" function.) It's precisely criterion 2 which implies no consumption of any (mutable) external state. I would think the two statements are equivalent.

– Peter A. Schneider
3 hours ago














5 Answers
5






active

oldest

votes


















57














Here are a few counterexamples that do not change the outer scope but are still considered impure:




  • function a() { return Date.now(); }

  • function b() { return window.globalMutableVar; }

  • function c() { return document.getElementById("myInput").value; }


  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)


Accessing non-constant non-local variables is enough to be able to violate the second condition.



I always think of the two conditions for purity as complementary:




  • the result evaluation must not have effects on side state

  • the evaluation result must not be affected by side state


The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.






share|improve this answer





















  • 1





    Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

    – Magnus
    13 hours ago











  • Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

    – sleske
    11 hours ago








  • 11





    If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

    – Holger
    11 hours ago











  • @Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

    – Bergi
    7 hours ago






  • 1





    @Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

    – Bergi
    6 hours ago



















6














It seems to me that the second condition you have described is a weaker constraint than the first.



Let me give you an example, suppose you have a function to add one that also logs to the console:



function addOneAndLog(x) {
console.log(x);
return x + 1;
}


The second condition you supplied is satisfied: this function always returns the same output when given the same input. It is, however, not a pure function because it includes the side effect of logging to the console.



A pure function is, strictly speaking, a function that satisfies the property of referential transparency. That is the property that we can replace a function application with the value it produces without changing the behaviour of the program.



Suppose we have a function that simply adds:



function addOne(x) {
return x + 1;
}


We can replace addOne(5) with 6 anywhere in our program and nothing will change.



By contrast, we cannot replace addOneAndLog(x) with the value 6 anywhere in our program without changing behaviour because the first expression results in something being written to the console whereas the second one does not.



We consider any of this extra behaviour that addOneAndLog(x) performs besides returning output as a side-effect.






share|improve this answer
























  • "It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

    – sleske
    12 hours ago











  • @sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

    – TheInnerLight
    10 hours ago











  • Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

    – TheInnerLight
    10 hours ago











  • What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

    – sleske
    10 hours ago








  • 1





    It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

    – sleske
    10 hours ago



















6














The "normal" way of phrasing what a pure function is, is in terms of referential transparency. A function is pure if it is referentially transparent.



Referential Transparency, roughly, means that you can replace the call to the function with its return value or vice versa at any point in the program, without changing the meaning of the program.



So, for example, if C's printf were referentially transparent, these two programs should have the same meaning:



printf("Hello");


and



5;


and all of the following programs should have the same meaning:



5 + 5;

printf("Hello") + 5;

printf("Hello") + printf("Hello");


Because printf returns the number of characters written, in this case 5.



It gets even more obvious with void functions. If I have a function void foo, then



foo(bar, baz, quux);


should be the same as



;


I.e. since foo returns nothing, I should be able to replace it with nothing without changing the meaning of the program.



It is clear, then, that neither printf nor foo are referentially transparent, and thus neither of them are pure. In fact, a void function can never be referentially transparent, unless it is a no-op.



I find this definition much easier to handle as the one you gave. It also allows you to apply it at any granularity you want: you can apply it to individual expressions, to functions, to entire programs. It allows you, for example, to talk about a function like this:



func fib(n):
return memo[n] if memo.has_key?(n)
return 1 if n <= 1
return memo[n] = fib(n-1) + fib(n-2)


We can analyze the expressions that make up the function and easily conclude that they are not referentially transparent and thus not pure, since they use a mutable data structure, namely the memo array. However, we can also look at the function and can see that it is referentially transparent and thus pure. This is sometimes called external purity, i.e. a function that appears pure to the outside world, but is implemented impure internally.



Such functions are still useful, because while impurity infects everything around it, the external pure interface builds a kind of "purity barrier", where the impurity only infects the three lines of the function, but does not leak out into the rest of the program. These three lines are much easier to analyze for correctness than the entire program.






share|improve this answer





















  • 1





    That impurity affects the whole program once you have concurrency.

    – R..
    3 hours ago



















3














You could have a source of randomness from outside the system. Say part of your calculation includes the room temperature. Executing the function will yield different results each time (depending on the external random element) but you don't really change the state of your program by executing it.



All I can think of, anyway.






share|improve this answer



















  • 3





    According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

    – Joseph M. Dion
    19 hours ago



















0















If the first condition is always true, are there any times the second
condition is not true?




Yes



Consider simple code snippet below



public int Sum(int a, int b){
Random rnd = new Random();
return rnd.Next(1, 10);
}


This code will return random output for same given set of inputs - however it does not have any side effect.



The overall effect of both the points #1 & #2 you mentioned when combined together means : At any point of time if function Sum with same i/p is replaced with its result in a program, overall meaning of program does not change. This is nothing but Referential transparency.






share|improve this answer


























  • But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

    – Right leg
    11 hours ago











  • @Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

    – Rahul Agarwal
    11 hours ago






  • 2





    Doesn't it change the state of the random generator?

    – Eric Duminil
    10 hours ago






  • 1





    Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

    – TheInnerLight
    10 hours ago






  • 1





    rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

    – Sneftel
    8 hours ago











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54992302%2fpure-functions-does-no-side-effects-imply-always-same-output-given-same-inp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























5 Answers
5






active

oldest

votes








5 Answers
5






active

oldest

votes









active

oldest

votes






active

oldest

votes









57














Here are a few counterexamples that do not change the outer scope but are still considered impure:




  • function a() { return Date.now(); }

  • function b() { return window.globalMutableVar; }

  • function c() { return document.getElementById("myInput").value; }


  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)


Accessing non-constant non-local variables is enough to be able to violate the second condition.



I always think of the two conditions for purity as complementary:




  • the result evaluation must not have effects on side state

  • the evaluation result must not be affected by side state


The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.






share|improve this answer





















  • 1





    Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

    – Magnus
    13 hours ago











  • Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

    – sleske
    11 hours ago








  • 11





    If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

    – Holger
    11 hours ago











  • @Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

    – Bergi
    7 hours ago






  • 1





    @Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

    – Bergi
    6 hours ago
















57














Here are a few counterexamples that do not change the outer scope but are still considered impure:




  • function a() { return Date.now(); }

  • function b() { return window.globalMutableVar; }

  • function c() { return document.getElementById("myInput").value; }


  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)


Accessing non-constant non-local variables is enough to be able to violate the second condition.



I always think of the two conditions for purity as complementary:




  • the result evaluation must not have effects on side state

  • the evaluation result must not be affected by side state


The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.






share|improve this answer





















  • 1





    Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

    – Magnus
    13 hours ago











  • Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

    – sleske
    11 hours ago








  • 11





    If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

    – Holger
    11 hours ago











  • @Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

    – Bergi
    7 hours ago






  • 1





    @Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

    – Bergi
    6 hours ago














57












57








57







Here are a few counterexamples that do not change the outer scope but are still considered impure:




  • function a() { return Date.now(); }

  • function b() { return window.globalMutableVar; }

  • function c() { return document.getElementById("myInput").value; }


  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)


Accessing non-constant non-local variables is enough to be able to violate the second condition.



I always think of the two conditions for purity as complementary:




  • the result evaluation must not have effects on side state

  • the evaluation result must not be affected by side state


The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.






share|improve this answer















Here are a few counterexamples that do not change the outer scope but are still considered impure:




  • function a() { return Date.now(); }

  • function b() { return window.globalMutableVar; }

  • function c() { return document.getElementById("myInput").value; }


  • function d() { return Math.random(); } (which admittedly does change the PRNG, but is not considered observable)


Accessing non-constant non-local variables is enough to be able to violate the second condition.



I always think of the two conditions for purity as complementary:




  • the result evaluation must not have effects on side state

  • the evaluation result must not be affected by side state


The term side effect only refers to the first, the function modifying the non-local state. However, sometimes read operations are considered as side effects as well: when they are operations and involve writing as well, even if their primary purpose is to access a value. Examples for that are generating a pseudo-random number that modifies the generator's internal state, reading from an input stream that advances the read position, or reading from an external sensor that involves a "take measurement" command.







share|improve this answer














share|improve this answer



share|improve this answer








edited 6 hours ago

























answered 21 hours ago









BergiBergi

375k60569900




375k60569900








  • 1





    Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

    – Magnus
    13 hours ago











  • Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

    – sleske
    11 hours ago








  • 11





    If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

    – Holger
    11 hours ago











  • @Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

    – Bergi
    7 hours ago






  • 1





    @Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

    – Bergi
    6 hours ago














  • 1





    Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

    – Magnus
    13 hours ago











  • Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

    – sleske
    11 hours ago








  • 11





    If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

    – Holger
    11 hours ago











  • @Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

    – Bergi
    7 hours ago






  • 1





    @Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

    – Bergi
    6 hours ago








1




1





Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

– Magnus
13 hours ago





Thanks Bergi. For some reason I thought side effects included reading variables outside of local scope, but I guess it is only a side effect if it writes such external variables.

– Magnus
13 hours ago













Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

– sleske
11 hours ago







Note that the two conditions are actually logically independent: This answer shows that 1. does not imply 2., but there are also many counterexamples that 2. does not imply 1. - for example, a function setDate(newDate) that sets the computer's current date to newDate has property 2. (the return value can be newDate or nothing), but it still violates 1. (it sets the current date).

– sleske
11 hours ago






11




11





If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

– Holger
11 hours ago





If prompt("you choose") does not have side effects, we should take a step back and clarify the meaning of side effects.

– Holger
11 hours ago













@Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

– Bergi
7 hours ago





@Holger OK, it's a bit of a stretch, probably even more so than Math.random(), but given a usual model of JavaScript computation, it does not change the observable environment - it does not violate OPs definition of "side effects (i.e. only changes to local scope are allowed)". But you're right, I will change it to something less controversial.

– Bergi
7 hours ago




1




1





@Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

– Bergi
6 hours ago





@Magnus Yes, exactly that's what effect means. I'll try to clarify in my answer as well, I didn't expect such large attention and want to make answer worthy of dozens of votes :-)

– Bergi
6 hours ago













6














It seems to me that the second condition you have described is a weaker constraint than the first.



Let me give you an example, suppose you have a function to add one that also logs to the console:



function addOneAndLog(x) {
console.log(x);
return x + 1;
}


The second condition you supplied is satisfied: this function always returns the same output when given the same input. It is, however, not a pure function because it includes the side effect of logging to the console.



A pure function is, strictly speaking, a function that satisfies the property of referential transparency. That is the property that we can replace a function application with the value it produces without changing the behaviour of the program.



Suppose we have a function that simply adds:



function addOne(x) {
return x + 1;
}


We can replace addOne(5) with 6 anywhere in our program and nothing will change.



By contrast, we cannot replace addOneAndLog(x) with the value 6 anywhere in our program without changing behaviour because the first expression results in something being written to the console whereas the second one does not.



We consider any of this extra behaviour that addOneAndLog(x) performs besides returning output as a side-effect.






share|improve this answer
























  • "It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

    – sleske
    12 hours ago











  • @sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

    – TheInnerLight
    10 hours ago











  • Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

    – TheInnerLight
    10 hours ago











  • What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

    – sleske
    10 hours ago








  • 1





    It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

    – sleske
    10 hours ago
















6














It seems to me that the second condition you have described is a weaker constraint than the first.



Let me give you an example, suppose you have a function to add one that also logs to the console:



function addOneAndLog(x) {
console.log(x);
return x + 1;
}


The second condition you supplied is satisfied: this function always returns the same output when given the same input. It is, however, not a pure function because it includes the side effect of logging to the console.



A pure function is, strictly speaking, a function that satisfies the property of referential transparency. That is the property that we can replace a function application with the value it produces without changing the behaviour of the program.



Suppose we have a function that simply adds:



function addOne(x) {
return x + 1;
}


We can replace addOne(5) with 6 anywhere in our program and nothing will change.



By contrast, we cannot replace addOneAndLog(x) with the value 6 anywhere in our program without changing behaviour because the first expression results in something being written to the console whereas the second one does not.



We consider any of this extra behaviour that addOneAndLog(x) performs besides returning output as a side-effect.






share|improve this answer
























  • "It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

    – sleske
    12 hours ago











  • @sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

    – TheInnerLight
    10 hours ago











  • Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

    – TheInnerLight
    10 hours ago











  • What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

    – sleske
    10 hours ago








  • 1





    It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

    – sleske
    10 hours ago














6












6








6







It seems to me that the second condition you have described is a weaker constraint than the first.



Let me give you an example, suppose you have a function to add one that also logs to the console:



function addOneAndLog(x) {
console.log(x);
return x + 1;
}


The second condition you supplied is satisfied: this function always returns the same output when given the same input. It is, however, not a pure function because it includes the side effect of logging to the console.



A pure function is, strictly speaking, a function that satisfies the property of referential transparency. That is the property that we can replace a function application with the value it produces without changing the behaviour of the program.



Suppose we have a function that simply adds:



function addOne(x) {
return x + 1;
}


We can replace addOne(5) with 6 anywhere in our program and nothing will change.



By contrast, we cannot replace addOneAndLog(x) with the value 6 anywhere in our program without changing behaviour because the first expression results in something being written to the console whereas the second one does not.



We consider any of this extra behaviour that addOneAndLog(x) performs besides returning output as a side-effect.






share|improve this answer













It seems to me that the second condition you have described is a weaker constraint than the first.



Let me give you an example, suppose you have a function to add one that also logs to the console:



function addOneAndLog(x) {
console.log(x);
return x + 1;
}


The second condition you supplied is satisfied: this function always returns the same output when given the same input. It is, however, not a pure function because it includes the side effect of logging to the console.



A pure function is, strictly speaking, a function that satisfies the property of referential transparency. That is the property that we can replace a function application with the value it produces without changing the behaviour of the program.



Suppose we have a function that simply adds:



function addOne(x) {
return x + 1;
}


We can replace addOne(5) with 6 anywhere in our program and nothing will change.



By contrast, we cannot replace addOneAndLog(x) with the value 6 anywhere in our program without changing behaviour because the first expression results in something being written to the console whereas the second one does not.



We consider any of this extra behaviour that addOneAndLog(x) performs besides returning output as a side-effect.







share|improve this answer












share|improve this answer



share|improve this answer










answered 21 hours ago









TheInnerLightTheInnerLight

10.4k11943




10.4k11943













  • "It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

    – sleske
    12 hours ago











  • @sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

    – TheInnerLight
    10 hours ago











  • Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

    – TheInnerLight
    10 hours ago











  • What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

    – sleske
    10 hours ago








  • 1





    It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

    – sleske
    10 hours ago



















  • "It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

    – sleske
    12 hours ago











  • @sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

    – TheInnerLight
    10 hours ago











  • Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

    – TheInnerLight
    10 hours ago











  • What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

    – sleske
    10 hours ago








  • 1





    It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

    – sleske
    10 hours ago

















"It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

– sleske
12 hours ago





"It seems to me that the second condition you have described is a weaker constraint than the first." No, the two conditions are logically independent.

– sleske
12 hours ago













@sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

– TheInnerLight
10 hours ago





@sleske you are mistaken. I have provided clear definitions for the terms pure and side-effect. Within these constraints, there is nothing that a function with no side effects besides return the same output for a given input. I have however provided examples where the second condition can be satisfied without the first. The fundamnetal concept to understand the notion of purity is referential transparency.

– TheInnerLight
10 hours ago













Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

– TheInnerLight
10 hours ago





Small typo: There is nothing that a function with no side effects can do besides returning the same output for a given input.

– TheInnerLight
10 hours ago













What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

– sleske
10 hours ago







What about something like returning the current time? That does not have side effects, but it does return a different output for the same input. Or more generally, any function where the result depends not only on the input parameters, but also on a (changeable) global variable.

– sleske
10 hours ago






1




1





It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

– sleske
10 hours ago





It seems you are using a different definition of "side effect" than what is commonly used. A side effect is commonly defined as "an observable effect besides returning a value" or an "observable change in state" - see e.g. Wikipedia , this post on softwareengineering.SE. You are totally right that Date.now() is not pure/referentially transparent, but not because it has side-effects, but because its result depends on more than just its input.

– sleske
10 hours ago











6














The "normal" way of phrasing what a pure function is, is in terms of referential transparency. A function is pure if it is referentially transparent.



Referential Transparency, roughly, means that you can replace the call to the function with its return value or vice versa at any point in the program, without changing the meaning of the program.



So, for example, if C's printf were referentially transparent, these two programs should have the same meaning:



printf("Hello");


and



5;


and all of the following programs should have the same meaning:



5 + 5;

printf("Hello") + 5;

printf("Hello") + printf("Hello");


Because printf returns the number of characters written, in this case 5.



It gets even more obvious with void functions. If I have a function void foo, then



foo(bar, baz, quux);


should be the same as



;


I.e. since foo returns nothing, I should be able to replace it with nothing without changing the meaning of the program.



It is clear, then, that neither printf nor foo are referentially transparent, and thus neither of them are pure. In fact, a void function can never be referentially transparent, unless it is a no-op.



I find this definition much easier to handle as the one you gave. It also allows you to apply it at any granularity you want: you can apply it to individual expressions, to functions, to entire programs. It allows you, for example, to talk about a function like this:



func fib(n):
return memo[n] if memo.has_key?(n)
return 1 if n <= 1
return memo[n] = fib(n-1) + fib(n-2)


We can analyze the expressions that make up the function and easily conclude that they are not referentially transparent and thus not pure, since they use a mutable data structure, namely the memo array. However, we can also look at the function and can see that it is referentially transparent and thus pure. This is sometimes called external purity, i.e. a function that appears pure to the outside world, but is implemented impure internally.



Such functions are still useful, because while impurity infects everything around it, the external pure interface builds a kind of "purity barrier", where the impurity only infects the three lines of the function, but does not leak out into the rest of the program. These three lines are much easier to analyze for correctness than the entire program.






share|improve this answer





















  • 1





    That impurity affects the whole program once you have concurrency.

    – R..
    3 hours ago
















6














The "normal" way of phrasing what a pure function is, is in terms of referential transparency. A function is pure if it is referentially transparent.



Referential Transparency, roughly, means that you can replace the call to the function with its return value or vice versa at any point in the program, without changing the meaning of the program.



So, for example, if C's printf were referentially transparent, these two programs should have the same meaning:



printf("Hello");


and



5;


and all of the following programs should have the same meaning:



5 + 5;

printf("Hello") + 5;

printf("Hello") + printf("Hello");


Because printf returns the number of characters written, in this case 5.



It gets even more obvious with void functions. If I have a function void foo, then



foo(bar, baz, quux);


should be the same as



;


I.e. since foo returns nothing, I should be able to replace it with nothing without changing the meaning of the program.



It is clear, then, that neither printf nor foo are referentially transparent, and thus neither of them are pure. In fact, a void function can never be referentially transparent, unless it is a no-op.



I find this definition much easier to handle as the one you gave. It also allows you to apply it at any granularity you want: you can apply it to individual expressions, to functions, to entire programs. It allows you, for example, to talk about a function like this:



func fib(n):
return memo[n] if memo.has_key?(n)
return 1 if n <= 1
return memo[n] = fib(n-1) + fib(n-2)


We can analyze the expressions that make up the function and easily conclude that they are not referentially transparent and thus not pure, since they use a mutable data structure, namely the memo array. However, we can also look at the function and can see that it is referentially transparent and thus pure. This is sometimes called external purity, i.e. a function that appears pure to the outside world, but is implemented impure internally.



Such functions are still useful, because while impurity infects everything around it, the external pure interface builds a kind of "purity barrier", where the impurity only infects the three lines of the function, but does not leak out into the rest of the program. These three lines are much easier to analyze for correctness than the entire program.






share|improve this answer





















  • 1





    That impurity affects the whole program once you have concurrency.

    – R..
    3 hours ago














6












6








6







The "normal" way of phrasing what a pure function is, is in terms of referential transparency. A function is pure if it is referentially transparent.



Referential Transparency, roughly, means that you can replace the call to the function with its return value or vice versa at any point in the program, without changing the meaning of the program.



So, for example, if C's printf were referentially transparent, these two programs should have the same meaning:



printf("Hello");


and



5;


and all of the following programs should have the same meaning:



5 + 5;

printf("Hello") + 5;

printf("Hello") + printf("Hello");


Because printf returns the number of characters written, in this case 5.



It gets even more obvious with void functions. If I have a function void foo, then



foo(bar, baz, quux);


should be the same as



;


I.e. since foo returns nothing, I should be able to replace it with nothing without changing the meaning of the program.



It is clear, then, that neither printf nor foo are referentially transparent, and thus neither of them are pure. In fact, a void function can never be referentially transparent, unless it is a no-op.



I find this definition much easier to handle as the one you gave. It also allows you to apply it at any granularity you want: you can apply it to individual expressions, to functions, to entire programs. It allows you, for example, to talk about a function like this:



func fib(n):
return memo[n] if memo.has_key?(n)
return 1 if n <= 1
return memo[n] = fib(n-1) + fib(n-2)


We can analyze the expressions that make up the function and easily conclude that they are not referentially transparent and thus not pure, since they use a mutable data structure, namely the memo array. However, we can also look at the function and can see that it is referentially transparent and thus pure. This is sometimes called external purity, i.e. a function that appears pure to the outside world, but is implemented impure internally.



Such functions are still useful, because while impurity infects everything around it, the external pure interface builds a kind of "purity barrier", where the impurity only infects the three lines of the function, but does not leak out into the rest of the program. These three lines are much easier to analyze for correctness than the entire program.






share|improve this answer















The "normal" way of phrasing what a pure function is, is in terms of referential transparency. A function is pure if it is referentially transparent.



Referential Transparency, roughly, means that you can replace the call to the function with its return value or vice versa at any point in the program, without changing the meaning of the program.



So, for example, if C's printf were referentially transparent, these two programs should have the same meaning:



printf("Hello");


and



5;


and all of the following programs should have the same meaning:



5 + 5;

printf("Hello") + 5;

printf("Hello") + printf("Hello");


Because printf returns the number of characters written, in this case 5.



It gets even more obvious with void functions. If I have a function void foo, then



foo(bar, baz, quux);


should be the same as



;


I.e. since foo returns nothing, I should be able to replace it with nothing without changing the meaning of the program.



It is clear, then, that neither printf nor foo are referentially transparent, and thus neither of them are pure. In fact, a void function can never be referentially transparent, unless it is a no-op.



I find this definition much easier to handle as the one you gave. It also allows you to apply it at any granularity you want: you can apply it to individual expressions, to functions, to entire programs. It allows you, for example, to talk about a function like this:



func fib(n):
return memo[n] if memo.has_key?(n)
return 1 if n <= 1
return memo[n] = fib(n-1) + fib(n-2)


We can analyze the expressions that make up the function and easily conclude that they are not referentially transparent and thus not pure, since they use a mutable data structure, namely the memo array. However, we can also look at the function and can see that it is referentially transparent and thus pure. This is sometimes called external purity, i.e. a function that appears pure to the outside world, but is implemented impure internally.



Such functions are still useful, because while impurity infects everything around it, the external pure interface builds a kind of "purity barrier", where the impurity only infects the three lines of the function, but does not leak out into the rest of the program. These three lines are much easier to analyze for correctness than the entire program.







share|improve this answer














share|improve this answer



share|improve this answer








edited 9 hours ago

























answered 13 hours ago









Jörg W MittagJörg W Mittag

292k63357552




292k63357552








  • 1





    That impurity affects the whole program once you have concurrency.

    – R..
    3 hours ago














  • 1





    That impurity affects the whole program once you have concurrency.

    – R..
    3 hours ago








1




1





That impurity affects the whole program once you have concurrency.

– R..
3 hours ago





That impurity affects the whole program once you have concurrency.

– R..
3 hours ago











3














You could have a source of randomness from outside the system. Say part of your calculation includes the room temperature. Executing the function will yield different results each time (depending on the external random element) but you don't really change the state of your program by executing it.



All I can think of, anyway.






share|improve this answer



















  • 3





    According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

    – Joseph M. Dion
    19 hours ago
















3














You could have a source of randomness from outside the system. Say part of your calculation includes the room temperature. Executing the function will yield different results each time (depending on the external random element) but you don't really change the state of your program by executing it.



All I can think of, anyway.






share|improve this answer



















  • 3





    According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

    – Joseph M. Dion
    19 hours ago














3












3








3







You could have a source of randomness from outside the system. Say part of your calculation includes the room temperature. Executing the function will yield different results each time (depending on the external random element) but you don't really change the state of your program by executing it.



All I can think of, anyway.






share|improve this answer













You could have a source of randomness from outside the system. Say part of your calculation includes the room temperature. Executing the function will yield different results each time (depending on the external random element) but you don't really change the state of your program by executing it.



All I can think of, anyway.







share|improve this answer












share|improve this answer



share|improve this answer










answered 21 hours ago









user3340459user3340459

8027




8027








  • 3





    According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

    – Joseph M. Dion
    19 hours ago














  • 3





    According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

    – Joseph M. Dion
    19 hours ago








3




3





According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

– Joseph M. Dion
19 hours ago





According to me, these "randomness from outside the system" are a form of side effect. Functions with these behaviors are not "pures".

– Joseph M. Dion
19 hours ago











0















If the first condition is always true, are there any times the second
condition is not true?




Yes



Consider simple code snippet below



public int Sum(int a, int b){
Random rnd = new Random();
return rnd.Next(1, 10);
}


This code will return random output for same given set of inputs - however it does not have any side effect.



The overall effect of both the points #1 & #2 you mentioned when combined together means : At any point of time if function Sum with same i/p is replaced with its result in a program, overall meaning of program does not change. This is nothing but Referential transparency.






share|improve this answer


























  • But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

    – Right leg
    11 hours ago











  • @Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

    – Rahul Agarwal
    11 hours ago






  • 2





    Doesn't it change the state of the random generator?

    – Eric Duminil
    10 hours ago






  • 1





    Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

    – TheInnerLight
    10 hours ago






  • 1





    rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

    – Sneftel
    8 hours ago
















0















If the first condition is always true, are there any times the second
condition is not true?




Yes



Consider simple code snippet below



public int Sum(int a, int b){
Random rnd = new Random();
return rnd.Next(1, 10);
}


This code will return random output for same given set of inputs - however it does not have any side effect.



The overall effect of both the points #1 & #2 you mentioned when combined together means : At any point of time if function Sum with same i/p is replaced with its result in a program, overall meaning of program does not change. This is nothing but Referential transparency.






share|improve this answer


























  • But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

    – Right leg
    11 hours ago











  • @Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

    – Rahul Agarwal
    11 hours ago






  • 2





    Doesn't it change the state of the random generator?

    – Eric Duminil
    10 hours ago






  • 1





    Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

    – TheInnerLight
    10 hours ago






  • 1





    rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

    – Sneftel
    8 hours ago














0












0








0








If the first condition is always true, are there any times the second
condition is not true?




Yes



Consider simple code snippet below



public int Sum(int a, int b){
Random rnd = new Random();
return rnd.Next(1, 10);
}


This code will return random output for same given set of inputs - however it does not have any side effect.



The overall effect of both the points #1 & #2 you mentioned when combined together means : At any point of time if function Sum with same i/p is replaced with its result in a program, overall meaning of program does not change. This is nothing but Referential transparency.






share|improve this answer
















If the first condition is always true, are there any times the second
condition is not true?




Yes



Consider simple code snippet below



public int Sum(int a, int b){
Random rnd = new Random();
return rnd.Next(1, 10);
}


This code will return random output for same given set of inputs - however it does not have any side effect.



The overall effect of both the points #1 & #2 you mentioned when combined together means : At any point of time if function Sum with same i/p is replaced with its result in a program, overall meaning of program does not change. This is nothing but Referential transparency.







share|improve this answer














share|improve this answer



share|improve this answer








edited 11 hours ago

























answered 12 hours ago









Rahul AgarwalRahul Agarwal

1,66831129




1,66831129













  • But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

    – Right leg
    11 hours ago











  • @Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

    – Rahul Agarwal
    11 hours ago






  • 2





    Doesn't it change the state of the random generator?

    – Eric Duminil
    10 hours ago






  • 1





    Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

    – TheInnerLight
    10 hours ago






  • 1





    rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

    – Sneftel
    8 hours ago



















  • But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

    – Right leg
    11 hours ago











  • @Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

    – Rahul Agarwal
    11 hours ago






  • 2





    Doesn't it change the state of the random generator?

    – Eric Duminil
    10 hours ago






  • 1





    Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

    – TheInnerLight
    10 hours ago






  • 1





    rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

    – Sneftel
    8 hours ago

















But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

– Right leg
11 hours ago





But in this case, the first condition is not verified: writing to the console is considered a side effect, since it changes the state of the machine itself.

– Right leg
11 hours ago













@Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

– Rahul Agarwal
11 hours ago





@Rightleg thx for pointing it out. Somehow I misunderstood OP totally other way. corrected answer.

– Rahul Agarwal
11 hours ago




2




2





Doesn't it change the state of the random generator?

– Eric Duminil
10 hours ago





Doesn't it change the state of the random generator?

– Eric Duminil
10 hours ago




1




1





Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

– TheInnerLight
10 hours ago





Generating a random number is itself a side effect, unless the state of the random number generator is supplied explicitly which would make the function satisfy condition 2.

– TheInnerLight
10 hours ago




1




1





rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

– Sneftel
8 hours ago





rnd doesn't escape the function, so the fact that its state changes doesn't matter to the purity of the function, but the fact that the Random constructor uses the current time as a seed value means that there are "inputs" other than a and b.

– Sneftel
8 hours ago


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54992302%2fpure-functions-does-no-side-effects-imply-always-same-output-given-same-inp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Couldn't open a raw socket. Error: Permission denied (13) (nmap)Is it possible to run networking commands...

VNC viewer RFB protocol error: bad desktop size 0x0I Cannot Type the Key 'd' (lowercase) in VNC Viewer...

Why not use the yoke to control yaw, as well as pitch and roll? Announcing the arrival of...