2

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

**(it is common in procedural programming paradigm).I know**

`While`

*Mathematica*'s functional programming paradigm is very elegent,so I'd like to use the function

**to rewrite the the construct of**

`NestWhile`

**.**

`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!

1Try using

`{derivative,k}`

in place of`Sequence[derivative,k]`

andeither (1) use`Apply`

with your`CompoundExpression[...]&`

, i.e.,`CompoundExpression[...]&@@#&`

, or (2) change`#1`

and`#2`

to`#[[1]]`

and`#[[2]]`

, respectively. – kglr – 2014-09-04T08:41:51.740@kguler,thanks:),there is no warning information appeared with your suggestion.However,I feel this program is stuck in a vicious circle.Namely,it cannot achieve correct result. – xyz – 2014-09-04T08:57:33.777

related: Can every usage of While be changed into NestWhile?

– Karsten 7. – 2014-09-04T09:16:07.587