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

Calculate Landau's function

How to number subfigures in Serbian Cyrillic?

Fishing from underwater domes

What's the origin of the concept of alternate dimensions/realities?

Can a human variant take proficiency in initiative?

Is there anything in the universe that cannot be compressed?

How can I store milk for long periods of time?

How many possible file types in the output `ls -l` command?

Heavy Box Stacking

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

LINQ Extension methods MinBy and MaxBy

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

Sum and average calculator

Could a simple hospital oxygen mask protect from aerosol poison?

Create a list of snaking numbers under 50,000

Moving DNS hosting for Active site to Route 53 - with G Suite MX TTL of 1 week

How would a disabled person earn their living in a medieval-type town?

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

Could a complex system of reaction wheels be used to propel a spacecraft?

Do universities maintain secret textbooks?

Padding a column of lists

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

Cheap oscilloscope showing 16 MHz square wave

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



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 9 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

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單