0
$\begingroup$

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}
$\endgroup$
2
  • 6
    $\begingroup$ change -> to :> as in /. {{a_, b_} :> ((a + # &) /@ b)} $\endgroup$ Dec 21, 2018 at 16:59
  • $\begingroup$ Thank you - why did this work? $\endgroup$
    – octopus
    Dec 21, 2018 at 17:51

2 Answers 2

3
$\begingroup$

Lists 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}*)
$\endgroup$
1
$\begingroup$

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

Your Answer

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

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