[Date Index]
[Thread Index]
[Author Index]
RE: pure functions
*To*: mathgroup at smc.vnet.net
*Subject*: [mg23296] RE: [mg23237] pure functions
*From*: "David Park" <djmp at earthlink.net>
*Date*: Sun, 30 Apr 2000 21:13:46 -0400 (EDT)
*Sender*: owner-wri-mathgroup at wolfram.com
> From: Helge Andersson [mailto:helgea at inoc.chalmers.se]
To: mathgroup at smc.vnet.net
>
> Of all the nice functions such as Map, Mapall, Thread, Apply .... I have
> not been able to write a simple code to generate the following
> procedure.
>
> I have a two dimensional list like
>
> li={{11,12,13,..},{21,22,23,...},{31,32,33,..},...}
>
> Since i like to use the pure function command I would like to map my
> pure function with arguments #1,#2,#3,.... on all the sublists in li.
>
> Let me exemplify with a simple pure function that add to numbers.
> (#1+#2)&
>
> if exli={{1,2},{3,4},{5,6},{7,8}}
>
> then I want to get the result
> {3,7,11,15}
>
> One solution, but not allways suitable for me, is the following
>
> (#1+#2)&[Sequence @@ Transpose[exli]].
>
> I want to get rid of the Transpose command and if possible also making
> use of the /@ notation for Map. Since I have seen so many elegant
> examples in the mailing lists I hope I can get something out of this.
>
> Finally, When using pure functions inside Mathematica defined functions
> such as Select for instance,
> Select[{1,2,3,4,5,6},#>3&]
> why don't we need to specify the argument list after the &sign. I can
> figure out that in this case the list sent to the Select command will be
> used as argument list for the pure function but how does this work in
> general. Which are the functions where this feature is possible?
>
> /Helge
>
Helge,
You have a pure function of two arguments. A list of two items is only one
argument. The standard way to handle this is to use Apply or @@. If f is
your pure function, f[{a,b}] will not work, but f@@{a,b} works. So for your
example:
datalist = Table[{Random[Integer, {0, 10}], Random[Integer, {0, 10}]}, {5}]
{{5, 3}, {0, 1}, {3, 1}, {10, 0}, {4, 2}}
Apply[#1 + #2 &, #] & /@ datalist
{8, 1, 4, 10, 6}
Notice, that we have one pure function inside another pure function.
Mathematica keeps track of which slot goes with which function. The above
can also be written:
#1 + #2 & @@ # & /@ datalist
{8, 1, 4, 10, 6}
As to your second question: sometimes Mathematica calls for the name of a
function, such as the f in
f[x,y] and sometimes it calls for an expression such as f[x,y]. A pure
function can stand in the place of a name of a function. It is easy to
become confused as to whether a function name or an expression is being
called for, and the documentation is not always too clear. So you just have
to read carefully and sometimes experiment.
David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/
Prev by Date:
**Re: pure functions**
Next by Date:
**Re: pure functions**
Previous by thread:
**Re: pure functions**
Next by thread:
**Re: pure functions**
| |