2
$\begingroup$

Obviously, the following code leads to an infinite loop:

(* TimeConstrained is used to avoid crash *)
TimeConstrained[
  NestWhileList[# + 1 &, 1, # > 0 &], 1]

But why this does not?

TimeConstrained[
  NestWhileList[# + 1 &, 1, True], 1]
(* ==> {1} *)

I use Mathematica 11.3 on windows 10.

$\endgroup$
2
$\begingroup$

Because True[1] === True evaluates to False.

The third argument of NestWhileList is supposed to be a function that has to be applied to the current iterate. The first time this function does not evaluate to True, the iteration is stopped and the current iterate is returned as last element of the returned list.

$\endgroup$
  • 1
    $\begingroup$ I try to use True& instead, and it gives an infinite loop, just as your analysis. Thanks! $\endgroup$ – stone-zeng Aug 3 '18 at 8:02
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Aug 3 '18 at 8:03

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.