Re: mathematica newbie trouble
- To: mathgroup at smc.vnet.net
- Subject: [mg99303] Re: [mg99276] mathematica newbie trouble
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Sat, 2 May 2009 05:59:30 -0400 (EDT)
- References: <200905010952.FAA02056@smc.vnet.net>
Hi, The point is that 1. SetDelayed is a scoping construct, and 2. It does not evaluate its rhs at the moment when assignment (definition) is made. The first point means that it creates bindings between formal parameters and the piece of code on the r.h.s (actually it relegates this to RuleDelayed in the rule it creates). The second means that It adds to the global rule base the delayed rule/definition (with its rhs not evaluated), whose contract is exactly the following: when, during evaluation, some expression matches the pattern of its lhs, take the (unevaluated) code on the rhs of the rule, find all occurrences of the parameters (names) on the lhs in this code, replace them by the actual parameters passed (present in evaluated expression that matched the rule/def pattern), and only then start evaluating the code. Thus, by the time the parameters (say, 3,4,5) are used, it does not know what "s" is (considers it a literal s), while by the time it starts to evaluate "s", the relations between the parameter names (a,b,c) and their actual values in this function call (3,4,5) (their bindings) are long gone (in fact, by that time all of the a,b,c-s in the original code have been replaced by 3,4,5), so a,b,c in s remain it their symbolic form. When you use Set, you force everything to evaluate at the moment of an assignment, and s gets rewritten into (a + b + c)/2 before the actual definition for <k> is formed. This problem is then avoided. However, using Set to define functions is generally inappropriate (there are exceptions). For example, your parameters a,b,c could have had global values, and then it wouldn't work as intended. In your particular case, a cleaner solution would be to use With: k[a_, b_, c_] := With[{s = (a + b + c)/2}, Sqrt[s (s - a) (s - b) (s - c)]]; Regards, Leonid On Fri, May 1, 2009 at 2:52 AM, Guapo <yangshuai at gmail.com> wrote: > i wrote the following mathematica code: > > s := (a + b + c)/2; > k[a_, b_, c_] := Sqrt[s (s - a) (s - b) (s - c)]; > k[3, 4, 5] > k[5, 9, 12] > > when run it, i can't get the write answer. but i change setDelayed(:=) > to set(=), everything works ok > > s = (a + b + c)/2; > k[a_, b_, c_] = Sqrt[s (s - a) (s - b) (s - c)]; > k[3, 4, 5] > k[5, 9, 12] > > i did a google search for the difference of set and setDelayed, > however, i still can't understand it for the upper described problem, > could anyone explain it? great thanks. > >
- References:
- mathematica newbie trouble
- From: Guapo <yangshuai@gmail.com>
- mathematica newbie trouble