3
$\begingroup$

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]}}
$\endgroup$

4 Answers 4

5
$\begingroup$

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]
$\endgroup$
5
$\begingroup$

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}}
$\endgroup$
3
$\begingroup$
{#[[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]}}

$\endgroup$
2
$\begingroup$
# /. {a_, b_, c_} :> {a, b, f[b, c]} & /@ list
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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