I have always been using Module when developing functions and scripts, although I can’t say that I understand the difference between Module and Block. Can’t anyone provide examples of when it is better to use one than the other?
Regards,
Gregory
I have always been using Module when developing functions and scripts, although I can’t say that I understand the difference between Module and Block. Can’t anyone provide examples of when it is better to use one than the other?
Regards,
Gregory
The documentation covers the the difference from a technical perspective here:
Modularity and the Naming of Things—Wolfram Documentation
Personally, I try to always use “With”. It’s behavior is the simplest and it fits well with Functional Programming. But I don’t want to cover it here since it would just confuse things.
Talking nontechnically, these are the cases when I use Module and Block:
Module = The most frequently used. Use when you define functions and you need some local variables that will change state.
Block = Use when considering a hypothetical world where a global variable is a different value. For example, there is a global variable $AllowInternet which is usually set to True. This controls whether Mathematica should allow itself to pull things from the internet. Say you want to run the function “f” but you want to see how it would behave if $AllowInternet were set to False. You would run:
Block[{ $AllowInternet = False}, f[]]
If you’re not sure wether to use Module or Block, you probably want Module. See this full post on this subject here:
http://mathematica.stackexchange.com/questions/559/what-are-the-use-cases-for-different-scoping-constructs
There is also nice topic on SE:
Oh no. I updated the article with the link and then saw you posted it as well.
So techncially you probably posted the link before I did.
Then I kinda fretted a bit because I was worried you’d think I had stolen the link from you and added it to my own answer. But I completely didn’t mean to. Sorry.
Hi Sean and Kuba,
Thanks for clarification. I think I get it (or am starting to)!
Regards,
Gregory