> foo := proc (p,q) local k; add((p[k]-q[k])^2,k=1..2) end proc; foo(a,b);
foo := proc(p, q) local k; add((p[k] - q[k])^2, k = 1 .. 2) end proc
2 2
(a[1] - b[1]) + (a[2] - b[2])
> fooo := codegen[optimize](foo); fooo(a,b);
fooo :=
proc(p, q) local t4; t4 := (p[k] - q[k])^2; add(t4, k = 1 .. 2) end proc
2
2 (a[k] - b[k])
First, notice that the 'local k' has disappeared, leaving k as a
reference to the global variable k.
Second notice that the expression has been moved out of add()
and assigned to the new local variable t4. Local variables have
first-evaluation semantics, so the variable is not re-evaluated
for each of add()'s iteration over k.
The corrected optimized function would be:
fooc := proc(p, q)
local k, t4;
t4 := (p[k] - q[k])^2; add(eval(t4), k = 1 .. 2)
end proc:
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers