MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: What is a good way of returning a function from a Module[]?


On 18 Nov., 11:12, Peter Pein <pet... at dordos.net> wrote:
> Szabolcs Horv=E1t schrieb:
>
>
>
>
>
> > What is an elegant way of returning a function from a Module[]?
>
> > Module[{a, b}, a = 1; b = a+1; (a+b+#)&] does not work because
> > Function[] holds its arguments.
>
> > The best way I could find was
>
> > Module[{p, q}, p = 1; q = p+1; With[{a = p, b = q}, (a+b+#)&]]
>
> > Is there a nicer/more concise way of doing this?  This is a simplified
> > example, but the important points are:
>
> > 1. The returned function may depend on more than one parameter ('a' and
> > 'b'; let's forget that in this case their sum could have been computed
> > inside the Module[]).
>
> > 2. 'a' and 'b' are not calculated independently.  The value of 'a' is
> > needed to find 'b'
>
> > Szabolcs
>
> In Version 5.2:
>
> map Evaluate onto the function:
>
> Module[{a, b}, a = 1; b = a + 1;
>    Evaluate /@ (a + b + #1 & )]
>
> 3 + #1 &
>
> This works even for functions with arguments which got names already
> used in the module:
>
> Module[{a, b, x = Pi, y = E},
>   a = 1; b = a + 1; Evaluate /@
>     Function[{x, y}, (a + b + x)/
>       (y - b + a)]]
>
> Function[{x$, y$}, (3 + x$)/(-1 + y$)]
>
> Peter- Zitierten Text ausblenden -
>
> - Zitierten Text anzeigen -

Hello

You do not even need Map. You can just wrap your Function body into an
Evaluate:

Module[{a, b}, a = 1; b = a + 1; Evaluate[a + b + #1] & ]

Best Regards
Norbert Marxer




  • Prev by Date: SeriesCoefficient: needs work!
  • Next by Date: Re: classes.m
  • Previous by thread: Re: What is a good way of returning a function from a Module[]?
  • Next by thread: Given a matrix A, construct a semi-orthogonal matrix L