6
$\begingroup$

I have a very long list of rules, and using this list of rules I want to see how some elements evolve as I successively apply the next rules on the previous rule.

Here is the simpler version of my problem, but I don't have any clue how to proceed. What would be an approach to this problem?

ClearAll[Evaluate[StringJoin[Context[], "*"]]]
Needs["Utilities`CleanSlate`"];
CleanSlate[];
ClearInOut[];

myRules = {a5 -> a4/a3, a4 -> a3 + a2,
           a3 -> a2^2 + a1, a2 -> a1 - 1, a1 -> b};

I wanted to get this list

{
    myRules[[1]] //. myRules[[2]],

    myRules[[1]] //. myRules[[2]] //.
    myRules[[3]],

    myRules[[1]] //. myRules[[2]] //.
    myRules[[3]] //. myRules[[4]],

    myRules[[1]] //. myRules[[2]] //.
    myRules[[3]] //. myRules[[4]] //.
    myRules[[5]]
}
$\endgroup$
3
  • 1
    $\begingroup$ Does Rest@FoldList[#1 /. #2 &, myRules] do the trick? Is that what you wanted? Something that just automates what you wrote down? $\endgroup$
    – march
    Aug 6 '20 at 21:36
  • $\begingroup$ @march, If my question seems to be silly , i'm extremely sorry. Your code is super (just in one line). Truly thanks a lot. $\endgroup$ Aug 6 '20 at 21:45
  • $\begingroup$ The question's not silly. I just wasn't sure what you wanted, so I asked to clarify in order to see if I should write an answer or not. I have written an answer below. $\endgroup$
    – march
    Aug 6 '20 at 21:47
9
$\begingroup$

Here is a quick one-liner.

myRules = {a5 -> a4/a3, a4 -> a3 + a2, a3 -> a2^2 + a1, a2 -> a1 - 1, a1 -> b};  
Rest@FoldList[#1 /. #2 &, myRules]
(* {a5 -> (a2 + a3)/a3,
    a5 -> (a1 + a2 + a2^2)/(a1 + a2^2),
    a5 -> (-1 + (-1 + a1)^2 + 2 a1)/((-1 + a1)^2 + a1),
    a5 -> (-1 + (-1 + b)^2 + 2 b)/((-1 + b)^2 + b)} *)

Which is the same output as we get from the OP's code.

Alternatively, do

Rest@FoldList[ReplaceAll, myRules]

(Thanks to Lukas-Lang.)

$\endgroup$
1
  • 2
    $\begingroup$ You should be able to write ReplaceAll instead of #1 /. #2& to improve readability (depending on who you ask of course) $\endgroup$
    – Lukas Lang
    Aug 7 '20 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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