Message Boards Message Boards

2
|
13131 Views
|
4 Replies
|
10 Total Likes
View groups...
Share
Share this post:

When Should I Use Module and When Block?

Posted 9 years ago

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

POSTED BY: Gregory Lypny
4 Replies

The documentation covers the the difference from a technical perspective here: https://reference.wolfram.com/language/tutorial/BlocksComparedWithModules.html

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

POSTED BY: Sean Clarke

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.

POSTED BY: Sean Clarke
Posted 9 years ago

Hi Sean and Kuba,

Thanks for clarification. I think I get it (or am starting to)!

Regards,

Gregory

POSTED BY: Gregory Lypny
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract