[Date Index]
[Thread Index]
[Author Index]
Re: Sequence is funny !
*To*: mathgroup at smc.vnet.net
*Subject*: [mg8952] Re: [mg8852] Sequence is funny !
*From*: Allan Hayes <hay at haystack.demon.co.uk>
*Date*: Mon, 6 Oct 1997 01:59:20 -0400
*Sender*: owner-wri-mathgroup at wolfram.com
Gilles BARBIER <Gilles.Barbier at der.edfgdf.fr>
[mg8852] Sequence is funny !
writes
> For some people who like to understand the internal mechanism
> of Mathematica, I give them this little problem a friend sent to me > :
> Why Table[i,{i,Sequence[1,3]}] gives {1,2,3,4} instead of {1,2,3} > !!
> That's not a bug, I even have an explanation,if you are interested.
Giles,
Very interesting.
Before giving my own explanation here is another teaser:
1/Sequence[2,3,4,5]
2^3^2^(2/5)
Now for Table[i,{i,Sequence[1,3]}].
Table[expr,{i,b}] evaluates as follows
a) Find the number of entries required in the table:
n = Floor[1+(b-1)] (Floor allows for b's like 7/2 and 7.8).
b) Compute n entries starting from 1 and incrementing by 1:
1, 1+1, ,1+(n-1)
The example Table[i,{i,Sequence[1,3]}] evaluates as follows.
a) Since table has attribute HoldAll, Sequence[1,3] is passed into
the calculation as b (Sequence is *not* stripped off immediately to
give Table[
i,{i,1,3}] ).
So we have
n = Floor[1+(Sequence[1,3]-1)]
-->Floor[1 + Plus[1,3,-1]] (*note this*)
--> Floor[1+3]
-->4
b) entries = 1, 2, 3, 4
NOTES:
(1) More generally, Table[expr, {i,a,b,s}] evaluates as follows
Find the number of entries required in the table:
n = Floor[1+((b-a)/s)]
Compute n entries starting from a incrementing by s:
a, a+s, ,a+(n-1)s
(default a is 1 and default s is 1)
(2) We can show that HoldAll is crucial in the example:
ClearAttributes[Table,HoldAll]
Table[i,{i,Sequence[1,3]}]
{1,2,3}
Explanation: Table[i,{i,Sequence[1,3]}] is changed first to
Table[i,{i,1,3}]
.
SetAttributes[Table,HoldAll] (*restore HoldAll*)
(3) The use of parentheses is important in Floor[1+(Sequence[1,3]-1)]
With them we have
Floor[1+(Sequence[1,3]-1)]
4
but without them we get
Floor[1+Sequence[1,3]-1]
Floor::"argx":
"\!\(Floor\) called with \!\(2\) arguments; 1 argument is
expected."
Floor[1,3]
(4) We can follow the steps in all these calculations:
On[]
On::"trace": "\!\(On[]\) --> \!\(Null\)."
Now evaluate the following:
Floor[1+(Sequence[1,3]-1)]
Table[i,{i,Sequence[1,3]}]
Off[]
Allan Hayes
hay at haystack.demon.co.uk
http://www.haystack.demon.co.uk/training.html
voice:+44 (0)116 2714198
fax: +44 (0)116 2718642
Leicester, UK
Prev by Date:
**Re: Sequence is funny !**
Next by Date:
**Re: prograMing: split a list**
Previous by thread:
**Re: Sequence is funny !**
Next by thread:
**Re: Re: Sequence is funny !**
| |