[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Axiom-math] Re: [Axiom-developer] Summing over a list
From: |
Bill Page |
Subject: |
Re: [Axiom-math] Re: [Axiom-developer] Summing over a list |
Date: |
Wed, 23 May 2007 19:40:44 -0400 |
User-agent: |
Webmail 4.0 |
Quoting Martin Rubey:
(redirecting to axiom-math, where usage questions belong)
Alasdair McAndrew writes:
Given two lists,for example:
z:=[1,2,3,4,5,6]
w:=[1,0,0,1,1,1]
it seems that the sum of the pairwise product is obtained by
reduce(+,[z.i*w.i for i in 1..6])3B
...
which is all very well. But why doesn't
sum(z.i*w.i,i=1..6)
work? I mean, sum(i^2,i=1..6) is fine.
...
Short explanation: unlike Mma or Maple, in axiom evaluation is
extremely simple: first the arguments are evaluated, then the
function. So, in your case, first axiom tries to evaluate
z.i*w.i
and
i=1..6
but there is no operation elt (which the dot is syntactig sugar
for) that takes a list and a symbol -- try to type z.i into the
interpreter! To make things clearer, note that there *is* an
operation "=" that takes a symbol and a segment.
As I mentioned in another thread on macros in Lisp, there
is a possible way to write the 'sum' operation in Axiom that
avoids this "premature evaluation" by using macros in Spad
or the interpreter:
(1) -> macro Sum(x, j,z) == reduce(+,[x for j in z])
Type: Void
\(2) -> z:=[1,2,3,4,5,6]
(2) [1,2,3,4,5,6]
Type: List PositiveInteger
(3) -> w:=[1,0,0,1,1,1]
(3) [1,0,0,1,1,1]
Type: List NonNegativeInteger
(4) -> Sum(z.i*w.i, i,1..6)
(4) 16
Type: PositiveInteger
-------
I would really like to write it like this:
(5) -> macro Sum(x,z) == reduce(+,[x for variable(z) in segment(z)])
Line 1: macro Sum(x,z) == reduce(+,[x for variable(z) in segment(z)])
..........................................A
Error A: syntax error at top level
Error A: Possibly missing a IN
2 error(s) parsing
So then I could have written:
Sum(z.i*w.i,i=1..6)
but Axiom's parser seems a little too strict. I think this
also illustrates a point about Lisp macros that would
presumably allow me to write such a thing (syntax not
withstanding). Maybe something like this?
(5) -> macro Sum(x,z) == (local j; j=:variable(z); _
reduce(+,[x for j in segment(z)]))
Type: Void
(6) -> Sum(z.i*w.i , i=1..6)
There are no library operations named :
Use HyperDoc Browse or issue
)what op:
to learn if there is any operation containing ": " in its name.
Cannot find a definition or applicable library operation named :
with argument type(s)
Symbol
Perhaps you should use "@" to indicate the required return type,
or "$" to specify which version of the function you need.
-----
But Axiom's interpreter seems to choke on it. :-(
Regards,
Bill Page.