Re: Something in the spirit of letrec
- To: mathgroup at smc.vnet.net
- Subject: [mg68460] Re: Something in the spirit of letrec
- From: Peter Pein <petsie at dordos.net>
- Date: Sun, 6 Aug 2006 02:56:31 -0400 (EDT)
- References: <eauvlv$172$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Mariano Suárez-Alvarez schrieb:
> Hi all,
>
> I'm trying to somehow come up with a function WithSelf such that
> evaluating
>
> WithSelf[{a,self[1]+b,self[2]+2}]
>
> will result in {a,a+b,a+b+c}. The idea is that the each
> item in the argument may depend on the previous ones;
> so for example "self[1]+b" means "what's in the first position
> in this list, plus b". There will be no "forward references"
> in the argument.
>
> I've tried with
>
> SetAttributes[WithSelf, HoldFirst];
> WithSelf[l_, self_] := Module[{ll, r = {}},
> ll = Function[self, #] & /@ l;
> Scan[AppendTo[r, #[r]] &, ll];
> r
> ]
>
> This gives the correct correct results, but emits warnings:
> for example,
>
> WithSelf[{1, self[[1]] + 2, self[[2]] + 3, self[[1]]}, self]
>
> results in {1, 3, 6, 1}, which is OK, but emits a few of
>
> Part::partd: Part specification self[[1]] is longer than depth of
> object.
>
> I guess there is some evaluation going on which I am
> not seeing...
>
> I'm quite sure what I am trying to do is possible... but how?
>
> Ideas?
>
> -- m
>
Hi Mariano,
how about
In[1]:= WithSelf[l_, s_:self] := l //. s -> (l[[#1]] & )
In[2]:= WithSelf[{1, self[1] + 2, self[2] + 3, self[1]}]
Out[2]= {1, 3, 6, 1}
?
Peter