4
$\begingroup$

I think I am missing something simple, so I apologize in advance...

I have two lists

{-1 - $\epsilon$ + 1/2 $\epsilon^2$ x''[0], 1 - $\epsilon$ + 1/2 $\epsilon^2$ x''[0]}

and

{x''[0]-> -1, x''[0]->1}

I simply want to replace x''[0] in the first item of the first list with the rule in the first item of the second list, and so on. I have tried using Thread[] but I must have the wrong syntax.

I am using this in a class demo, so if it is possible to do this in the least Mathematica way possible (please don't throw things), that would be greatly appreciated :)

$\endgroup$

2 Answers 2

9
$\begingroup$

You can useMapThread:

list = {-1 - ϵ + 1/2 ϵ^2 x''[0],  1 - ϵ + 1/2 ϵ^ 2 x''[0]};
rules = {x''[0] -> -1, x''[0] -> 1};

MapThread[ReplaceAll,  {list, rules}]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

You can also use Inner as follows:

Inner[ReplaceAll, list, rules, List]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

How to do it with Thread:

If you use Thread you need to wrap ReplaceAll[...] with Unevaluated to prevent ReplaceAll being evaluated before Thread gets to do its job:

Thread[Unevaluated[ReplaceAll[list, rules]]]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

Another way to use Thread:

ReplaceAll @@@ Thread[{list, rules}]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

Least Mathematica way:

My candidate for doing this in the least Mathematicaesq way in Mathematica is:

For[results = {}; i = 1, i <= 2, i++, AppendTo[results, list[[i]] /. rules[[i]]]]
results

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

Halloween specials:

☺ = # /. #2 & @@@ ({##}\[Transpose]) &;
☺[list, rules]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

☺☺ = {# /. #3, #2 /. #4} & @@ (## & @@@ {##}) &;
☺☺[list, rules]

{-1 - ϵ - ϵ^2/2, 1 - ϵ + ϵ^2/2}

$\endgroup$
1
  • $\begingroup$ Ahh perfect, thank you! The "Halloween special" gave me a good laugh! $\endgroup$
    – dpholmes
    Sep 25, 2019 at 10:34
4
$\begingroup$

"The least Mathematica way possible"? Something like this?

lst = {-1 - ϵ + 1/2 ϵ2 x''[0], 1 - ϵ + 1/2 ϵ2 x''[0]};

rules = {x''[0] -> -1, x''[0] -> 1};

Table[ lst[[i]] /. rules[[i]], {i, Length@rules}]
$\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.