Re: Nesting functional commands
- To: mathgroup at smc.vnet.net
- Subject: [mg102934] Re: Nesting functional commands
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Wed, 2 Sep 2009 04:05:52 -0400 (EDT)
On 9/1/09 at 3:51 AM, enoel2 at gmail.com (Erin Noel) wrote:
>So how would you go about nesting a functional command inside of
>another functional command? For example, say A={1,2,3,4}, then
>3*#&/@A = {3,6,9,12}. No problem. But then what if, within that
>vector {3,6,9,12}, I wanted to use the Select command to choose
>elements less than, say 7. The command Select[3*#&/@A,#<7&] doesn't
>work because, as far as I can tell, Mathematica doesn't know which
>"#" belongs to Select and which "#" belongs to the &/@ mapping over
>A. I know that I could define 3*#&/@A as a new variable and then use
>that new variable in the Select command, but is there any way to
>nest multiple commands in this way?
You can do what you are trying to do with either
In[28]:= Select[(3 # & /@ a), # > 7 &]
Out[28]= {9,12}
or
In[27]:= Select[Map[3 # &, a], # > 7 &]
Out[27]= {9,12}
However, both of these are doing more work than is needed in
this case. Times as the attribute Listable. So,
In[29]:= Select[3 a, # > 7 &]
Out[29]= {9,12}
which is also more readable code.
Note, I've used a lower case a as the variable rather than an
uppercase A since it is generally not a good idea to use
uppercase letters as variables. Using lower case letters is
guaranteed to avoid conflicts with built in symbols and functions.