       Re: Apply a function to parts of a list

• To: mathgroup at smc.vnet.net
• Subject: [mg110306] Re: Apply a function to parts of a list
• From: Bill Rowe <readnews at sbcglobal.net>
• Date: Sun, 13 Jun 2010 04:08:13 -0400 (EDT)

```On 6/12/10 at 5:32 AM, rui.rojo at gmail.com (Rui) 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

Perhaps pattern matching, i.e.,

In:= {{a, 5}, {b, 6}} /. {x_, y_Integer} -> {x, y/2}

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

But note

In:= {{a, 5}, {b, 6}} /. {x_, y_} -> {x, y/2}

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

This last happens since the pattern {x_,y_} matches
{{a,5},{b,6}} which is why I restricted the match in the second
position to integers. But if the list were longer, i.e.,

In:= {{a, 5}, {b, 6}, {c, 7}} /. {x_, y_} -> {x, y/2}

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

there is no problem with the simpler pattern

```

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