Recently,I find the program of @J.M. about Get a "step-by-step" evaluation in Mathematica is a very useful example for learning Mathematica programming.
In the function WalkD,I see the construct of While(it is common in procedural programming paradigm).I know Mathematica's functional programming paradigm is very elegent,so I'd like to use the function NestWhile to rewrite the the construct of While.
Origin program:
WalkD[f_, x_] := Module[{derivative, oldderivative, k},
derivative = d[f, x]; displayStart[derivative];
(*First While construct*)
While[! FreeQ[derivative, d],
oldderivative = derivative; k = 0;
(*Second while construct*)
While[oldderivative == derivative,
k++;
derivative = derivative /.
ToExpression[StringReplace[$RuleNames[[k]], " " -> ""]]];
displayDerivative[derivative, k]];
D[f, x]]
My trial to rewrite the inner While construct
WalkDRewrite[f_, x_] :=
Module[
{derivative, oldderivative, k},
derivative = d[f, x];
displayStart[derivative];
While[! FreeQ[derivative, d],
oldderivative = derivative;
k = 0;
(*begin to rewrite*)
NestWhile[
CompoundExpression[#2++,
#1 = #1 /. ToExpression[StringReplace[$RuleNames[[k]], " " -> ""]]] &,
Sequence[derivative, k],
oldderivative != derivative
]
(*end *)
displayDerivative[derivative, k]
];
D[f, x]
]
However,I failed after debugging all morning.
Question:
Is it possible to use NestWhile to replace While?Thanks sincerely!
{derivative,k}in place ofSequence[derivative,k]and either (1) useApplywith yourCompoundExpression[...]&, i.e.,CompoundExpression[...]&@@#&, or (2) change#1and#2to#[[1]]and#[[2]], respectively. – kglr Sep 04 '14 at 08:41