Nested Functions alternative?
Jason Carver
jason.carver at gmail.com
Mon Jun 22 09:52:47 CDT 2009
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
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 2:37 AM, Carlo de Falco
carlo.defalco-at-gmail.com|public mailing list|
<s4djklmnu80t at sneakemail.com> wrote:
>
> On 21 Jun 2009, at 22:18, Jason Carver wrote:
>
> Since Octave doesn't support nested functions, is there a suggested
>> alternative for closures of non-trivial method size?
>>
>> For example, I want to do something like this:
>>
>> function f = sophisticated_func_many_args(arg2,arg3,arg4)
>> function ans = sophisticated_func_one_arg(arg1)
>> #do something with args 1-4 for several lines
>> #set answer
>> end
>> f = @sophisticated_func_one_arg
>> end
>>
>> one_arg_func = sophisticated_func_many_args(2,3,4)
>> result = built_in_library_call(one_arg_func)
>>
>
> maybe I'm missing the point here, but wouldn't
>
> function f = sophisticated_func_many_args (arg1, arg2, arg3, arg4)
> #do something with args 1-4 for several lines
> #set answer
> endfunction
>
> result = built_in_library_call(@(arg1) sophisticated_func_many_args
> (arg1,2,3,4))
>
> do what you want?
>
> This situation is particularly relevant when a library requires a
>> single-argument function passed in (eg~ ode45). Maybe I'm just spoiled with
>> python lately, but I don't even see the imperative workaround for this
>> anymore. What is the suggested alternative for this pattern in Octave?
>>
>> Cheers,
>> Carver
>>
>
>
> HTH,
> c.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: https://www-old.cae.wisc.edu/pipermail/help-octave/attachments/20090622/1f04ed5a/attachment.html
More information about the Help-octave
mailing list