Showing posts with label assignment. Show all posts
Showing posts with label assignment. Show all posts

Tuesday, June 9, 2015

Use Block to Temporarily Block Global Variables

The main Mathematica scoping function to learn is Module. For occasional special purposes, use Block to temporarily store and then restore Global variables, and use With to fix local variables so they can't be accidentally changed inside of With.

Use any Doc Center page for a scratchpad (not Block), since all variable names and values are localized to that page and are automatically cleaned up when you leave the page.

Block does two things:
  1. Temporarily stores a Global variable value and then restore it
  2. Uses a local value for the variable in the Block if you give it one
Here is a step-by-step example of how Block works.

x=17;
Block[{x=4},x^2]
16

x
17

Step
Effect
x = 17;
Variable x is Set to 17 in the Global` Context
Block[{x=4},x^2]
A Block is entered using specifying a local variable with the same name as the Global one (x = 4)
Within Block: x$23 = x
Local, temporary variable x$23 is Set to x’s global value of 17
Within Block: x = 4
Local, temporary variable x is Set to 4
Within Block: x^2
In Power[x, 2] x replaced by 4: Power[x, 2] /. x -> 4
Block returns 4^2 = 16
Locally with Block Power[x, 2] evaluates to 16, which is returned
Block Sets x = x$23 and exits
The Global value of x is restored
x
The Global values of x is called
17
The Global value of x is returned

Typical Uses of Block

Block is used to scope and protect the iterators in Table, Do, Sum, etc. If you write a function with an iterator you can use Block.

More typical uses of Block are to change the value of system environment variables such as decreasing $RecursionLimit or $IterationLimit to prevent infinite looping while you're debugging a function, or increasing them to solve a deeply nested or iterated calculation.

An interesting combinatorial series arises from the number of partitions of integer sets, the Bell number. Pemmaraju and Skiena compute it recursively. To let the function solve for indefinitely large sets, $RecursionLimit is temporarily set to Infinity within the Block and automatically restored to its default value after execution.

Clear[bellB,bellB1];

bellB@n_Integer:=bellB1@n;
bellB1@0=1;(*base case*)

bellB1@n_:=Block[
{$RecursionLimit=Infinity},
bellB1@n=Sum[Binomial[n-1,k]*bellB1@k,{k,0,n-1}] (*memo function*)
]

bellB/@Range@10
{1,2,5,15,52,203,877,4140,21147,115975}

$RecursionLimit

1024

Why Block Might Not Seem to Work

Again, if you understand that Block will 1) temporarily store a Global variable value and then restore it, and 2) use a local value for the variable in the Block only if you give it one, you will understand the following examples. First, we Set x equal to 25 in Global`.

x=25;

Here x isn't scoped and so isn't Blocked; Mathematica can't just assume you wanted it localized.

Block[{},x]
25

Here x is scoped but we didn't assign it a new value. So while its global value of 25 was stored in a temporary variable it was also used in Block.

Block[{x},x]
25

Now we assign a value to x in Block's scope, or in its body. Block works as intended.

Block[{x=5},x]
5

Block[{x},x=5]
5

And x's Global value was restored as Block closed itself out. All is good in the universe :-)

x
25


Block Compared with Module and With

Block and Module let us change scoped variable values in the body of their code.

Block[{x=5},Print@x;x=50;x]
5
50

Module[{x=15},Print@x;x=100;x]
15
100

But With does not; we get an error message. When we try to Set x to 8, Mathematica sees "2 = 8":

With[{x=2},Print@x;x=8;x^2]
2
Set::setraw: Cannot assign to raw object 2. >>
Out[292]= 4

Block and Module immediately use scoped variable values, so here Mathematica sees "5^2 /. 5 -> 6", evaluates 5^2 as 25 and thus sees "25 /. 5 ->6"; there's no x to replace.

Block[{x=5},x^2/.x->6]
25

Module works by creating a special local variable name for each scoped variable. Here, within the Module, x lives on under the new name "x$485":

Module[{x},Print@x]
x$485

Sunday, June 16, 2013

My 1985 Notes on Wolfram Harvard Talk on SMP - Precursor to Mathematica Part 1

Here is more Mathematicana to celebrate Mathematica's 25th Anniversary. Thanks to my friend and intellectual complement John Deming ('you might be interested in this'), I was present at the creation, at least to hear, with growing excitement as I sat in Aiken 101 at Harvard in 1985, one of Stephen's early talks on the Symbolic Manipulation Program, SMP, which became Mathematica. I have it on good authority that none other than Steve Jobs, marketing genius extraordinaire, came up with the name Mathematica when Stephen solicited outside suggestions.

So here are pp 1-3 of my notes transcribed and an image. I'm sure I misunderstood some of the talk, so if in doubt check the SMP Handbook, a fascinating bit of history itself. Regarding the note that SMP was "written in 120K lines of C" as of the date of the talk, in this period Stephen could write up to 1000 lines of C code in a day.



298(85)/3/11 15:30
Harvard, Aiken 101

Dr. S. Wolfram

Arithmetic, logarithms - now hardware is powerful enough to do math generally. We need a language. Needs to be general, interactive, extensible, efficient (able to do heavy duty problems), portable (able to run without change on many computers).

Intrinsic data types: numbers, arrays of numbers. But need types for higher level objects, too, algorithms for them, and symbolic manipulation of them. An intrinsic structure to deal with these.

SMP. Symbolic Manipulation Program, which I started 5 years ago. Now it's 120K lines of C code later. SMP contains the core of a fundamental mathematical language; plus programmability allowing definitions of new objects; graphics; and a [functions] library.

The basic objects are numbers; symbols such as "a", "Pi"; projections i.e. parts of objects; and lists to specify collections of objects. Assignment of symbols to "values". You specify specific values then add more general expressions or values to which the machine goes if the specific values do not apply.

Conditions: $a_ = (test) to say $a such that (test) is true.

[Handles] multigeneric functions such as the gamma function. [Piecewise functions? But I'm not sure I got this right-KWC]

$$x stands for sequence of expressions.

It's important to have well-defined rules for pattern-matching. [SMP] will pattern-match even when not asked to solve explicit mathematical functions.

:   immediate assignment
::  delayed assignment

[Uses?] the Frobenius method of series expansion of differential equations. Total differential equations. XDSol J Greif & SW [Caltech?] Oct 1981.

Euler-Mascheroni constant.

Hypergeometric functions are very difficult to evaluate. Often evaluates to yield no value. Factorization: [uses the] fastest code written (as opposed to Berlekamp's). Integration: Risch etc algorithms.

Canonical form used for simplification. Applies the chain rule to reduce and solve differential equations.

Manipulates expressions: as trees, graphically.

List Operations: APL + symbolic operations etc.

Lends itself to building up programs instinctively, because symbolic language, unlike numerical languages (C?)...

Strongly based on pattern-matching. explicit assignment of cases [i.e. piecewise functions] is more natural and better for mathematics than a series of if-then functions.

User can define input & output syntax

Code generation: Convert SMP to C or FORTRAN for numerical cases: compile & load code incorporated; and add intrinsic code to SMP.

Written in 120K lines of C, runs under UNIX, VMS, VM...

Multi-n-ary tree internal data structure
Memory management
sub-expression sharing mechanisms
compacting garbage collection
-> intermediate expressions > ~16Mb
Block transfer.

Pp 4-5 of the notes are here and contain some fascinating insights into the principles guiding Mathematica's development to this day and beyond.




Monday, January 2, 2012

Assignment to a Pattern


I'll use a couple of examples on searching Strings from Sal Mangano's excellent Mathematica Cookbook to show how to use Pattern Assignment. First, it's simple enough to search some Strings for those that are numbers:

StringMatchQ[{"12345", "2468", "abcde"}, NumberString]

{True, True, False}

But if you want to add a Predicate, you need another device such as naming a Pattern and using the name in the Predicate. This is an example of Pattern Assignment where the Pattern is named "m".

StringMatchQ[{"12345", "2468", "abcde"}, m : NumberString /; OddQ@FromDigits@m]

{True, False, False}

As Sal Mangone notes in his Mathematica Cookbook and I explore further in Predicates, Tests, and Test Patterns, adding a Predicate to a Pattern is a powerful device because we can include in the Predicate anything that Mathematica can compute. A Predicate can be a built-in one or one we construct, so the possibilities are truly limitless.