Best practice with Return in Module or BlockWhat are the use cases for different scoping constructs?Return struct from function (with DownValues)Syntax highlighter shows error for Manipulate when it's inside a Block or a ModuleImplementing local variables of a recursive function with either Module or BlockWhat is the difference between defining a function and specifying the type of argument, versus applying a test to that argument?Is anonymous pure function a scoping construct?How to prevent name clash between arguments of different functions?Difference between variables and functionsfunction fails to use local variable when it is called inside a ModuleModule - Symbols out of scope of lexical scopingScoping construct for dependent constants

Does Q ever actually lie?

How did the Altair 8800 front panel load the program counter?

Heavy Box Stacking

How does the search space affect the speed of an ILP solver?

Why does the U.S. military maintain their own weather satellites?

Necessity of tenure for lifetime academic research

German equivalent to "going down the rabbit hole"

awk print conditions

Can a human variant take proficiency in initiative?

Understanding data transmission rates over copper wire

An idiom for “Until you punish the offender, they will not give up offenses”

I failed to respond to a potential advisor

Calculate Landau's function

Why do presidential pardons exist in a country having a clear separation of powers?

Fishing from underwater domes

How to differentiate between two people with the same name in a story?

Did NASA/JPL get "waning" and "waxing" backwards in this video?

Quick Tilepaint Puzzles: Corridors and Corners

How were US credit cards verified in-store in the 1980's?

'spazieren' - walking in a silly and affected manner?

I was given someone else's visa, stamped in my passport

How smart contract transactions work?

Am I required to correct my opponent's assumptions about my morph creatures?

What is the motivation behind designing a control stick that does not move?



Best practice with Return in Module or Block


What are the use cases for different scoping constructs?Return struct from function (with DownValues)Syntax highlighter shows error for Manipulate when it's inside a Block or a ModuleImplementing local variables of a recursive function with either Module or BlockWhat is the difference between defining a function and specifying the type of argument, versus applying a test to that argument?Is anonymous pure function a scoping construct?How to prevent name clash between arguments of different functions?Difference between variables and functionsfunction fails to use local variable when it is called inside a ModuleModule - Symbols out of scope of lexical scopingScoping construct for dependent constants






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I am a bit confused on the use of Return in either Block or Module when defining a custom function that is used a lot. For instance, The two simple functions (not using initialisation to examplify)



f1[x_] := Module[y,y=x+1; Return[y];];
f2[x_] := Module[y,y=x+1; y];


I am familiar with the differences between Module and Block---see e.g. here---but I don't really understand what the difference between f1 and f2 are in the present case. As someone familiar with other languages, the first seems more natural than the second, especially with respect to the absence of a final semi-colon in the module.



I have noticed that with Return I get a bunch of variables y$1, y$2, ... that get out of scope and not in the other case, but I haven't used it enough to see if it happens also in that case.



Is there a fundamental difference between those two functions, and what is considered best practice?










share|improve this question











$endgroup$









  • 6




    $begingroup$
    Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
    $endgroup$
    – Szabolcs
    8 hours ago

















2












$begingroup$


I am a bit confused on the use of Return in either Block or Module when defining a custom function that is used a lot. For instance, The two simple functions (not using initialisation to examplify)



f1[x_] := Module[y,y=x+1; Return[y];];
f2[x_] := Module[y,y=x+1; y];


I am familiar with the differences between Module and Block---see e.g. here---but I don't really understand what the difference between f1 and f2 are in the present case. As someone familiar with other languages, the first seems more natural than the second, especially with respect to the absence of a final semi-colon in the module.



I have noticed that with Return I get a bunch of variables y$1, y$2, ... that get out of scope and not in the other case, but I haven't used it enough to see if it happens also in that case.



Is there a fundamental difference between those two functions, and what is considered best practice?










share|improve this question











$endgroup$









  • 6




    $begingroup$
    Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
    $endgroup$
    – Szabolcs
    8 hours ago













2












2








2





$begingroup$


I am a bit confused on the use of Return in either Block or Module when defining a custom function that is used a lot. For instance, The two simple functions (not using initialisation to examplify)



f1[x_] := Module[y,y=x+1; Return[y];];
f2[x_] := Module[y,y=x+1; y];


I am familiar with the differences between Module and Block---see e.g. here---but I don't really understand what the difference between f1 and f2 are in the present case. As someone familiar with other languages, the first seems more natural than the second, especially with respect to the absence of a final semi-colon in the module.



I have noticed that with Return I get a bunch of variables y$1, y$2, ... that get out of scope and not in the other case, but I haven't used it enough to see if it happens also in that case.



Is there a fundamental difference between those two functions, and what is considered best practice?










share|improve this question











$endgroup$




I am a bit confused on the use of Return in either Block or Module when defining a custom function that is used a lot. For instance, The two simple functions (not using initialisation to examplify)



f1[x_] := Module[y,y=x+1; Return[y];];
f2[x_] := Module[y,y=x+1; y];


I am familiar with the differences between Module and Block---see e.g. here---but I don't really understand what the difference between f1 and f2 are in the present case. As someone familiar with other languages, the first seems more natural than the second, especially with respect to the absence of a final semi-colon in the module.



I have noticed that with Return I get a bunch of variables y$1, y$2, ... that get out of scope and not in the other case, but I haven't used it enough to see if it happens also in that case.



Is there a fundamental difference between those two functions, and what is considered best practice?







functions scoping return-value






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago







Bulkilol

















asked 8 hours ago









BulkilolBulkilol

1334 bronze badges




1334 bronze badges










  • 6




    $begingroup$
    Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
    $endgroup$
    – Szabolcs
    8 hours ago












  • 6




    $begingroup$
    Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
    $endgroup$
    – Szabolcs
    8 hours ago







6




6




$begingroup$
Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
$endgroup$
– Szabolcs
8 hours ago




$begingroup$
Best practice is the 2nd (no Return). Return is a bit foreign to how Mathematica works, and also redundant here. There is absolutely no reason to add it (it doesn't improve readability for someone comfortable with Mathematica—quite the opposite). Note that Return returns from the function, not from the Module. If you had something wrapping the Module, the behaviour would be different.
$endgroup$
– Szabolcs
8 hours ago










1 Answer
1






active

oldest

votes


















2













$begingroup$

The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:



func[x_] := Module[
answer1,answer2,
<code>
If[isValid[answer1],
Return[answer1, Module]
];
<more code>
answer2
]


Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.



The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is not documented.






share|improve this answer









$endgroup$

















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "387"
    ;
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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%2fmathematica.stackexchange.com%2fquestions%2f204614%2fbest-practice-with-return-in-module-or-block%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2













    $begingroup$

    The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:



    func[x_] := Module[
    answer1,answer2,
    <code>
    If[isValid[answer1],
    Return[answer1, Module]
    ];
    <more code>
    answer2
    ]


    Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.



    The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is not documented.






    share|improve this answer









    $endgroup$



















      2













      $begingroup$

      The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:



      func[x_] := Module[
      answer1,answer2,
      <code>
      If[isValid[answer1],
      Return[answer1, Module]
      ];
      <more code>
      answer2
      ]


      Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.



      The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is not documented.






      share|improve this answer









      $endgroup$

















        2














        2










        2







        $begingroup$

        The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:



        func[x_] := Module[
        answer1,answer2,
        <code>
        If[isValid[answer1],
        Return[answer1, Module]
        ];
        <more code>
        answer2
        ]


        Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.



        The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is not documented.






        share|improve this answer









        $endgroup$



        The use case for Return is not to return a value at the end of a scoping construct like Module or Block, but to return something from the middle of the construct:



        func[x_] := Module[
        answer1,answer2,
        <code>
        If[isValid[answer1],
        Return[answer1, Module]
        ];
        <more code>
        answer2
        ]


        Here I check a whether some condition is satisfied, and if so I exit the Module early. This could be achieved with a Catch and Throw, but I tend to reserve that more for errors and exceptions. Here I view the Return as a normal operation, and not exceptional.



        The caveat here is that the 2-argument form of Return, where the second argument says what to return from, is not documented.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 4 hours ago









        Jason B.Jason B.

        50.5k3 gold badges94 silver badges201 bronze badges




        50.5k3 gold badges94 silver badges201 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Mathematica Stack Exchange!


            • 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.

            Use MathJax to format equations. MathJax reference.


            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%2fmathematica.stackexchange.com%2fquestions%2f204614%2fbest-practice-with-return-in-module-or-block%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

            ParseJSON using SSJSUsing AMPscript with SSJS ActivitiesHow to resubscribe a user in Marketing cloud using SSJS?Pulling Subscriber Status from Lists using SSJSRetrieving Emails using SSJSProblem in updating DE using SSJSUsing SSJS to send single email in Marketing CloudError adding EmailSendDefinition using SSJS

            Кампала Садржај Географија Географија Историја Становништво Привреда Партнерски градови Референце Спољашње везе Мени за навигацију0°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.340°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.34МедијиПодациЗванични веб-сајту

            19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу