How can I use replacement rules to match and work with a list. For example,
{1, {2, 3}} /. {{a_, b_} -> ((a + # &) /@ b)}
outputs
{2,3}
but I expected
{3,4}
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityLists have nothing to do with the problem. The reason why you obtained the result above is that ->
(Rule
) evaluates its arguments before going further. So
(a + # &) /@ b
inside your rule first evaluated to
b
resulting in the rule
{a_, b_} -> b
and only after that the replacement
{1, {2, 3}} /. {{a_, b_} -> b}
evaluated to {2, 3}
. You can use :>
(RuleDelayed
) to prevent the second argument of :>
from evaluation:
{1, {2, 3}} /. {{a_, b_} :> ((a + # &) /@ b)}
(*{3, 4}*)
Specifying b
with a head List
works
{1, {2, 3}} /. {a_, b_List} -> a + b
But why not just use Plus
:
Plus @@ {1, {2, 3}}
->
to:>
as in/. {{a_, b_} :> ((a + # &) /@ b)}
$\endgroup$