Message Boards Message Boards

0
|
8499 Views
|
11 Replies
|
12 Total Likes
View groups...
Share
Share this post:

Is Blocks vs. Modules documentation clear enough ?

Posted 10 years ago

What `Module[vars,body]` does is to treat the form of the expression body at the time when the module is executed as the "code" of a Mathematica program. Then when any of the vars explicitly appears in this "code", it is considered to be local. `Block[vars,body]` does not look at the form of the expression body. Instead, throughout the evaluation of body, the block uses local values for the vars.


This particular gobbet of useless pseudo-philosophical drivel has persisted throughout several iterations of Mathematica and its woefully inadequate documentation "system." Is there anyone on any of these forums capable of explaining the difference between modules and blocks?
POSTED BY: Ben Tompkins
11 Replies
Personally, I love documentation Center. Exactly because it has a lot of info - and a little search would give you this page:

Blocks Compared with Modules
POSTED BY: Sam Carrettie
You'll find a lot of information about this here:

What are the use cases for various scoping constructs?

I'll add that what Module does is called lexical scoping and what Block does is called dynamic scoping by computer scientists.  You'll find some theoretical information about both on Wikipedia: https://en.wikipedia.org/wiki/Scope_(computer_science)

The simple way to think about them as a beginner is this:  Module gives you local symbols.  Block just temporarily removes the definition of symbols, if they have any, otherwise it doesn't do anything.  If you need to localize something, use Module.  Use Block only if you know you need it and you understand why.

Example:
 In[1]:=
 f[sym_] := Module[{x}, D[x sym, x]]
 g[sym_] := Block[{x}, D[x sym, x]]
 
 In[3]:= f[a]
 Out[3]= a
 
 In[4]:= g[a]
 Out[4]= a

In[5]:= f[x]
Out[5]= x

In[6]:= g[x]
Out[6]= 2 x

The last one gives 2x because it calculates the derivative of x^2.  The x symbol that was passed into the funtion g is the same as the x symbol used inside Block.
POSTED BY: Szabolcs Horvát

I suspect that in the majority of cases, the performance win from using Block instead of Module is so minor that it's not worth bothering except after all other possible optimization opportunities have been exhausted.

In[6]:= Do[
   Block[{a = 1},
    Do[a++, {10}]
    ],
   {500000}
   ]; // Timing

Out[6]= {3.029107, Null}

In[7]:= Do[
   Module[{a = 1},
    Do[a++, {10}]
    ],
   {500000}
   ]; // Timing

Out[7]= {3.790960, Null}

This is of course an arbitrary example, and reducing the number of repetitions in the inner Do will make the differences look greater. But in most applications how much time is really spent in Module or Block doing their localization work vs evaluating the code inside Module or Block?

I'd say: only bother with this if there are no better ways to optimize and benchmarking shows clear wins. Usually there are better ways to optimize ...

POSTED BY: Szabolcs Horvát
A good example I have come across is from The Mathematica Book, Version 5, page 377. I hope this helps.
(* iabraham, Mathematica 7.0.1.0, Win-7-64b *)
Clear["Global`*"];
m = i^2
Block[{i = a}, i + m] (* Evaluates to a + a^2 *)
Module[{i = a}, i+ m] (* Evaluates to a + i^2 *)
Block allows the global definition of "m" to feedthrough, and take on the local value "i = a", resulting in (a + a^2). I like to visualize it a being very porus.

Module on the other hand uses the local value of "i = a" for any "i", and retains the unchanged global definition for "m", without allowing the "m = i^2" to become "m = a^2". Module is not porus and completely shields everything within from any global definitions.
POSTED BY: Isaac Abraham
Dear Ben, hello and welcome to the Wolfram Community! Here is the tutorial on posting you requested:

How to type up a post: editor tutorial & general tips


To edit your post – click “Edit” in the lower right corner of your post.
POSTED BY: Sam Carrettie
Posted 10 years ago
So my posting has been mangled by the system and I cannot find any doc on the editing system...
POSTED BY: Ben Tompkins
Posted 10 years ago
"Blocks Compared with Modules" is a good definitional description, but it could be improved by discussing intent and motivation:
  1. Why did the developers provide for both?
  2. Under what circumstances would you choose to use Block rather than Module? Give an example.
  3. Under what circumstances would you choose to use Module rather than Block? Give an example.
  4. What is recommended as the best coding practice and why?
This type of information allows for a much better understanding of the definitional description.
Regards,
David
POSTED BY: David Keith
Posted 10 years ago
Thanks, Szabolcs.
I followed the link. It is very useful.
POSTED BY: David Keith
Posted 10 years ago
It is now painfully obvious to everyone that not only am I rude but BB-illiterate as well. I am also a slow learner -- I must have hit the Reply link below Isaac's response at least 5 times and revisited my browser (Firefox 28.0/Mavericks) settings at least 3 times, disabled popup-blocking, enabled java, and randomly toggled a dozen other settings before I noticed the blank form at the bottom of the page under the unobtrusive heading  "Reply to this discussion."  Duhhh... Does this mean that I can only reply to the discussion as a whole and not to individuals? What, then is the point of repeating all those Reply links at the bottom of each reply? I am quite plainly out of my depth here. Is there a lifeguard on duty? One more thing -- when I hit Source the second time the text flashed for a fraction of a second in a different, much heavier, typeface before reverting to normal. What could that possibly mean? As for the Flag link -- I am honestly afraid to ask...
POSTED BY: Ben Tompkins
Posted 10 years ago
Ohhh! dumb me! Sorry, Isaac. jeez
POSTED BY: Ben Tompkins

Thanks Ben for starting this post and the others for their replies. I had the exact same question, and this helped. One "wrinkle" I would like to add is this: in one of the Mathematica online video workshops [Write Faster Code with Wolfram Language Virtual Workshop][1] it is suggested that it is better to use Block than Module (assuming you don't need any behavior specific to that construct) since Block is typically faster to execute. This seems to run opposite to the advice here that Module should be the default construct since it is easier to stay on top of things and not have mistakes appear to to Global values leaking in.

POSTED BY: T Saab
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