MathGroup Archive 2010

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

Search the Archive

Re: Apply a function to parts of a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110320] Re: Apply a function to parts of a list
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Sun, 13 Jun 2010 04:10:46 -0400 (EDT)

Hi Rui,

The methods you listed are perfectly fine IMO. You may want to consider a
rule-based solution as well:

In[1]:= Replace[{{a, 5}, {b, 6}, {c, 7}}, {a_, b_} :> {a, b/2}, 1]

Out[1]= {{a, 5/2}, {b, 3}, {c, 7/2}}

Using ReplaceAll may fail in some cases since the rule based on generic
patterns may sometimes be  applied one level higher than desired:

In[3]:= {{a, 5}, {b, 6}} /. {a_, b_} :> {a, b/2}

Out[3]= {{a, 5}, {b/2, 3}}


Regards,
Leonid


On Sat, Jun 12, 2010 at 2:32 AM, Rui <rui.rojo at gmail.com> wrote:

> I have always done very ugly code when trying to do something
> seemingly simple and basic such as applying a function to subparts of a
> list.
> Simple example, I want to divide by 2 all the second elements of a
> list
> {{a, 5}, {b, 6}, ...}   -->  {{a, 5/2}, ...}
>
> My ideas:
> Transpose -> MapAt/Map -> Transpose
> Build the sublist with Part and then rebuild it
> Use Map and a function like #[[All, 2]] and then rebuild it.
>
> I don't like any solution. I wanted to know if there's anything simple
> that I'm overseing
>
> Thanks guys
>
>


  • Prev by Date: Re: Find value of unknown const that causes integral to
  • Next by Date: Re: Find value of unknown const that causes integral to equal some
  • Previous by thread: Re: Apply a function to parts of a list
  • Next by thread: Re: Apply a function to parts of a list