MathGroup Archive 2012

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

Search the Archive

Re: can one make local symbol in a pure function?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg127386] Re: can one make local symbol in a pure function?
  • From: Bob Hanlon <hanlonr357 at gmail.com>
  • Date: Fri, 20 Jul 2012 23:41:40 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • Delivered-to: mathgroup-newout@smc.vnet.net
  • Delivered-to: mathgroup-newsend@smc.vnet.net
  • References: <20120720075152.D7B14688F@smc.vnet.net>

Clear[f, x]

f[x_] := Module[{a = 2}, x^a]

lst = Range[5];

f /@ lst

{1, 4, 9, 16, 25}

Function[{x}, Module[{a = 2}, x^a]] /@ lst

{1, 4, 9, 16, 25}

Module[{a = 2}, #^a] & /@ lst

{1, 4, 9, 16, 25}

With[{a = 2}, #^a & /@ lst]

{1, 4, 9, 16, 25}


Bob Hanlon


On Fri, Jul 20, 2012 at 3:51 AM, Nasser M. Abbasi <nma at 12000.org> wrote:
>
> I was learning a bit about pure functions.
> Suppose we have this toy example:
>
> -----------------
> Clear[f, x]
> f[x_] := Module[{a = 2}, x^a]
> lst = {1, 2, 3};
> Map[f[#] &, lst]
> -------------------
>
> ---> {1, 4, 9}
>
> Now I'd like to define the pure function
> in-line, using the Function[] syntax, but
> at the same time be able to make a local symbol
> 'a' like I did when using Module. But the
> syntax does not allow one to do that. There is
> no place to define it:
>
> ------------------
> lst = {1, 2, 3};
> Map[Function[{x}, x^2], lst]
> ----------------
>
> ---> {1, 4, 9}
>
> So if someone wants to make a temporary symbol to use
> for temporary calculation inside the pure function, like
> 'a' in this example, and at the same time not have it be global
> symbol, then one must use a Module? I can write
>
> ---------------------
> lst = {1, 2, 3};
> Map[Function[{x}, a=2; x^a], lst]
> ----------------------
>
> But now 'a' is global, while when using Module it
> was local.
>
> Any way to make local symbols in a pure function like
> with Module?
>
> thanks,
> --Nasser
>



  • Prev by Date: Re: FindCurvePath has a problem
  • Next by Date: Re: Finding a sum
  • Previous by thread: can one make local symbol in a pure function?
  • Next by thread: Re: can one make local symbol in a pure function?