Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a list of triplets:

list = {{1, 3, 5}, {4, 5, 1}, {4, 9, 2}}

How can I apply a function f to the last element of each triplet when f the last and second-to-last elements of each triplet as arguments? The result should look like:

{{1, 3, f[3, 5]}, {4, 5, f[5, 1]}, {4, 9, f[9, 2]}}

I tried:

list /. {a_, b_, c_} :> {a, b, f[b, c]}

But the result comes out as

{{1, 3, 5}, {4, 5, 1}, {f[4], f[9], f[2]}}
share|improve this question
add comment

4 Answers

up vote 5 down vote accepted

Here are two ways to do it.

data = {{1, 3, 5}, {4, 5, 1}, {4, 9, 2}};
Replace[data, {a_, b_, c_} :> {a, b, f[b, c]}, {1}]
{{1, 3, f[3, 5]}, {4, 5, f[5, 1]}, {4, 9, f[9, 2]}}
MapThread[{#1, #2, f[#2, #3]} &, data]
{{1, 3, f[3, 5]}, {4, 5, f[5, 1]}, {4, 9, f[9, 2]}}

A small variant of the last is

MapThread[{#1, #2, f[##2]} &, data]
share|improve this answer
add comment

When the sublists are short like in your example, I tend to use Apply:

 {#1, #2, f[#2, #3]}& @@@ {{1, 3, 5}, {4, 5, 1}, {4, 9, 2}}
share|improve this answer
add comment
{#[[1]], #[[2]], f[#[[2]], #[[3]]]} & /@ {{1, 3, 5}, {4, 5, 1}, {4, 9, 2}}

{{1, 3, f[3, 5]}, {4, 5, f[5, 1]}, {4, 9, f[9, 2]}}

share|improve this answer
add comment
# /. {a_, b_, c_} :> {a, b, f[b, c]} & /@ list
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.