Re: execution model: Function vs. delayed execution
- To: mathgroup at smc.vnet.net
- Subject: [mg121336] Re: execution model: Function vs. delayed execution
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Sun, 11 Sep 2011 07:28:55 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <j4fhvn$2gr$1@smc.vnet.net>
On 10/09/2011 12:34, Alan wrote: > Warning: I am a Mathematica newbie and not a CS type, so my vocabulary may prove clumsy. > > I am used to a deferred execution model of function definition. Roughly, if I can write code that would be successfully executed outside a function definition, then I can make it a function body by appropriately "wrapping" it. > > In Mathematica, I can evaluate the following): > x = {1,1,2} > x=DeleteDuplicates[x]; x > (Note: the redundancy is intentional.) > > Next, I attempt to "wrap" this as follows > Clear[x] > Function[x, (x=DeleteDuplicates[x];x)][{1,1,2}] > > This produces an error: > Set::shape: "Lists {1,1,2} and {1,2} are not the same shape." > > Can you help me understand the execution model that leads to this? > > Thanks, > Alan Isaac > > The problem is that in your original version x is a global variable, whereas in the second, it is the formal argument to your function - so you end up executing: {1,1,2}=DeleteDuplicates[{1,1,2}] The difference as compared with other computer languages that you may have used - e.g. C or Fortran - is that there x would be the name of a variable that holds the argument, rather than the argument itself - as it is in Mathematica. The ultimate reason for this difference, is that Mathematica is designed to solve both symbolic and numerical problems. So for example, you might want to write a function that takes a variable as argument that has no value. This would result in an operation on an undefined variable in C or Fortran. David Bailey http://www.dbaileyconsultancy.co.uk