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

Avoiding unpacking an array when altering its dimension

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

Use comma instead of & in table

Is there any relevance to Thor getting his hair cut other than comedic value?

What type of postprocessing gives the effect of people standing out

What is the difference between throw e and throw new Exception(e)?

What is better: yes / no radio, or simple checkbox?

What can I substitute for soda pop in a sweet pork recipe?

Auto Insert date into Notepad

Difference between 小吃 and 零食

Where was Karl Mordo in Infinity War?

chrony vs. systemd-timesyncd – What are the differences and use cases as NTP clients?

Does music exist in Panem? And if so, what kinds of music?

Equivalent to "source" in OpenBSD?

What is the difference between ashamed and shamed?

What to do when being responsible for data protection in your lab, yet advice is ignored?

How to approximate rolls for potions of healing using only d6's?

Accessing something inside the object when you don't know the key

How can atoms be electrically neutral when there is a difference in the positions of the charges?

Reason Why Dimensional Travelling Would be Restricted

Did 5.25" floppies undergo a change in magnetic coating?

How to avoid being sexist when trying to employ someone to function in a very sexist environment?

The change directory (cd) command is not working with a USB drive

Whom do I have to contact for a ticket refund in case of denied boarding (in the EU)?



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?












12















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

























  • 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
    2 hours ago
















12















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

























  • 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
    2 hours ago














12












12








12








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 pure-function






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 6 hours ago









Code-Apprentice

48k1490178




48k1490178










asked 8 hours ago









MagnusMagnus

1,42011026




1,42011026













  • 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
    2 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
    2 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
2 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
2 hours ago












4 Answers
4






active

oldest

votes


















20














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 prompt("you choose"); }


  • 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, the function doesn't need to have any side effect itself if it is going to be affected by other side effects.






share|improve this answer

































    3














    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































      2














      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



















      • 2





        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
        5 hours ago



















      -2














      I would say that the point 2 (Always return the same output, given the same input) is not a condition but a consequence of point 1 : a function without side effects will always return the same output given the same input.






      share|improve this answer



















      • 1





        That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

        – Code-Apprentice
        6 hours ago











      • It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

        – Mark
        5 hours ago






      • 1





        According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

        – Joseph M. Dion
        5 hours ago











      • That's not what a side effect means, @JosephM.Dion

        – jhpratt
        3 mins 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

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      20














      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 prompt("you choose"); }


      • 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, the function doesn't need to have any side effect itself if it is going to be affected by other side effects.






      share|improve this answer






























        20














        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 prompt("you choose"); }


        • 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, the function doesn't need to have any side effect itself if it is going to be affected by other side effects.






        share|improve this answer




























          20












          20








          20







          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 prompt("you choose"); }


          • 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, the function doesn't need to have any side effect itself if it is going to be affected by other side effects.






          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 prompt("you choose"); }


          • 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, the function doesn't need to have any side effect itself if it is going to be affected by other side effects.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 7 hours ago

























          answered 8 hours ago









          BergiBergi

          375k60566899




          375k60566899

























              3














              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




























                3














                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


























                  3












                  3








                  3







                  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 7 hours ago









                  TheInnerLightTheInnerLight

                  10.4k11943




                  10.4k11943























                      2














                      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



















                      • 2





                        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
                        5 hours ago
















                      2














                      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



















                      • 2





                        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
                        5 hours ago














                      2












                      2








                      2







                      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 8 hours ago









                      user3340459user3340459

                      7027




                      7027








                      • 2





                        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
                        5 hours ago














                      • 2





                        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
                        5 hours ago








                      2




                      2





                      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
                      5 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
                      5 hours ago











                      -2














                      I would say that the point 2 (Always return the same output, given the same input) is not a condition but a consequence of point 1 : a function without side effects will always return the same output given the same input.






                      share|improve this answer



















                      • 1





                        That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                        – Code-Apprentice
                        6 hours ago











                      • It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                        – Mark
                        5 hours ago






                      • 1





                        According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                        – Joseph M. Dion
                        5 hours ago











                      • That's not what a side effect means, @JosephM.Dion

                        – jhpratt
                        3 mins ago
















                      -2














                      I would say that the point 2 (Always return the same output, given the same input) is not a condition but a consequence of point 1 : a function without side effects will always return the same output given the same input.






                      share|improve this answer



















                      • 1





                        That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                        – Code-Apprentice
                        6 hours ago











                      • It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                        – Mark
                        5 hours ago






                      • 1





                        According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                        – Joseph M. Dion
                        5 hours ago











                      • That's not what a side effect means, @JosephM.Dion

                        – jhpratt
                        3 mins ago














                      -2












                      -2








                      -2







                      I would say that the point 2 (Always return the same output, given the same input) is not a condition but a consequence of point 1 : a function without side effects will always return the same output given the same input.






                      share|improve this answer













                      I would say that the point 2 (Always return the same output, given the same input) is not a condition but a consequence of point 1 : a function without side effects will always return the same output given the same input.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 6 hours ago









                      Joseph M. DionJoseph M. Dion

                      1724




                      1724








                      • 1





                        That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                        – Code-Apprentice
                        6 hours ago











                      • It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                        – Mark
                        5 hours ago






                      • 1





                        According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                        – Joseph M. Dion
                        5 hours ago











                      • That's not what a side effect means, @JosephM.Dion

                        – jhpratt
                        3 mins ago














                      • 1





                        That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                        – Code-Apprentice
                        6 hours ago











                      • It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                        – Mark
                        5 hours ago






                      • 1





                        According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                        – Joseph M. Dion
                        5 hours ago











                      • That's not what a side effect means, @JosephM.Dion

                        – jhpratt
                        3 mins ago








                      1




                      1





                      That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                      – Code-Apprentice
                      6 hours ago





                      That is the whole point of the question. The OP is asking why is it necessary to list both when it seems that one is a consequence of the other. However, the examples above show some good counter examples.

                      – Code-Apprentice
                      6 hours ago













                      It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                      – Mark
                      5 hours ago





                      It's possible to have a function with side effects but always returning the same output for an input (console.log(x);return x), and it's possible to have a function with no side effects that returns different values for a given input (return Date.now() + x). The two conditions are independent.

                      – Mark
                      5 hours ago




                      1




                      1





                      According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                      – Joseph M. Dion
                      5 hours ago





                      According to me, the function (return Date.now() + x) is a fonction WITH side effect because it reads something from the outside world (the time).

                      – Joseph M. Dion
                      5 hours ago













                      That's not what a side effect means, @JosephM.Dion

                      – jhpratt
                      3 mins ago





                      That's not what a side effect means, @JosephM.Dion

                      – jhpratt
                      3 mins 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

                      As a Security Precaution, the user account has been locked The Next CEO of Stack OverflowMS...

                      Список ссавців Італії Природоохоронні статуси | Список |...

                      Українські прізвища Зміст Історичні відомості |...