6
$\begingroup$

I am trying to store a boolean value into a variable with the additional property that the value changes each time the variable is called.

In = var

Out = True

In = var
Out = False

My approach was

var := If[
    TrueQ[var],
    var = False, 
    var = True
    ]

but this is not working. My guess is that is recurring when is calling TrueQ[var]; if this is the case I don't understand why I don't have a recursion limit error.

How can I make my code work?

$\endgroup$
13
$\begingroup$
flip = True;
var := flip = Not[flip]

var
(*False*)

var
(*True*)

var
(*False*)
$\endgroup$
4
$\begingroup$

Here is a way using delayed evaluation and recursive pure function. It allows to only use one variable:

ClearAll[var];
var := Function[Null, With[{res = ! #2}, # := #0[#, res]; res], HoldFirst][var, False]

So that:

var

(* True *)

var

(* False *)

var

(* True *)
$\endgroup$

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.