Nested Functions alternative?
Jason Carver
jason.carver at gmail.com
Mon Jun 22 12:32:40 CDT 2009
Ok, great, it's the 'persistent' keyword that I was missing. Thanks!
BTW, I got the Matlab nested function syntax from the zip file here:
http://www.mathworks.com/matlabcentral/fileexchange/18223
My code was consistent with that zip I think, so I'm not sure why it
wouldn't work.
Also, the sneakemail servers mangle the headers to make it look like it was
only sent to you, even though I cc'd help-octave at octave.org . Anyway I
messed up the last time and posted my "real" email for spammers everwhere,
so for clarity I stopped using sneakemail on this reply.
Thanks for all your help Carlo,
Carver
Slique.com - builds group memory by putting all your group's email, files
and documents in one place
I'm trying this out: http://five.sentenc.es/
On Mon, Jun 22, 2009 at 11:58 AM, Carlo de Falco
carlo.defalco-at-gmail.com|public mailing list|
<s4djklmnu80t at sneakemail.com> wrote:
>
> On 22 Jun 2009, at 16:52, ynj0qeh02 at sneakemail.com wrote:
>
> Thanks Carlo,
>>
>> I believe that solution won't work in general for a "stateful generator"
>> pattern, right? eg~
>>
>> ==anonymous function:
>>
>> function a = adder(a,b)
>> a = a+b;
>> end
>>
>> gen = @(b) adder(0,b) #anonymous function does not maintain state between
>> calls
>>
>> gen(1) -> 1
>> gen(1) -> 1
>> gen(1) -> 1
>>
>> ==nested function
>>
>> function f = adder(a)
>> #adder returns a stateful adding function that keeps track of the total
>> sum
>> function a = addon(b)
>> #addon adds b into the summation with each call, returning the cumulative
>> sum over all calls
>> a = a+b; #assign to state variable a
>> end
>> f = @addon
>> end
>>
>> gen = adder(0) #nested function maintains state between calls
>>
>> gen(1) -> 1
>> gen(1) -> 2
>> gen(1) -> 3
>>
>> ==
>>
>> Is it possible to accomplish the same effect as the nested function in
>> Octave? Despite the maintainers' (reasonable) warnings about code clarity,
>> there are some situations that would really benefit from this pattern.
>> (Apologies if my nested function example has any typos, I don't have access
>> to Matlab to test it)
>>
>> Thanks,
>> Carver
>>
>
> Again maybe I'm missing the big picture as I don't understand why you would
> need nested functions to accomplish what you propose, but I think you can
> doit as follows:
>
> >>function f = adder (a, b)
> persistent f = b;
> f += a;
> endfunction
> >> gen = @(a) adder(a, 0);
> >> gen (1)
> ans = 1
> >> gen (1)
> ans = 2
> >> gen (1)
> ans = 3
>
> HTH,
> c.
>
> P.S. please keep the list in CC when answering as someone else might
> be intersted in the topic
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: https://www-old.cae.wisc.edu/pipermail/help-octave/attachments/20090622/abff806e/attachment.html
More information about the Help-octave
mailing list