Message Boards Message Boards

0
|
2409 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How to turn a function off and on

I use the Echo[] function in order to help debug my code. However, I don't always want to execute an Echo[x] where x might be a variable (or expression) of interest. With that goal in mind, I created the function

If[flag == True,
  myEcho[x_] := If[myEchoFlag, Echo[x]],
  myEcho[x_] := Nothing;
  ];

So that if I want to see an output, I set the flag variable to True, otherwise I set it to False. My understanding is that in the case that flag is False, all the myEcho[x] calls would disappear. Often, the argument x is the result of a Plot command which can take time. At first, I thought that by using the

myEcho[x_] := Nothing;

version, this would skip the time-consuming execution of the x expression. That is not the case and after thinking about it I could understand how the expression x has to be evaluated first (therefore consuming time) before the interpreter figures out that the argument matches the pattern of being a match and thing assigning Nothing to the result.

On the other hand, as a programmer in more traditional languages (C,C++,C#), I was thinking that a compiler or interpreter would see that myEcho[anyPattern}] is Nothing and therefore would NOT EVEN compute the value of x, since no matter what comes out of the expression, the myEcho[x] should be Nothing.

Can anyone provide me with an alternative so that I have version of myEcho[x] which in one case of the flag variable simply calls the Echo[x], and in the other case is a "do nothing" expression that does not even compute the argument? I am pretty sure that there is a way, but would want to see what the experts say.

Thank you.

POSTED BY: Henrick Jeanty
3 Replies

This reminds me of that old discussion from three years ago.

POSTED BY: Henrik Schachner
Posted 1 year ago

First off, x_ isn't "any pattern" (it doesn't match multiple arguments, for example). So, the evaluator must evaluate the arguments before it can determine a match. The pattern ___ would be closer to "any pattern", but I don't know if even that would preempt evaluation of the argument.

But I wouldn't recommend this approach at all. I'd recommend using built in functions:

POSTED BY: Eric Rimbey

Here is my attempt. The sample code with embedded Echo is this:

Module[{}, x = Sqrt[2]; If[myEchoQ, Echo[x]]; N[x]]

The flag is called myEchoQ. When myEchoQ is set to False, no echo is generated and no unnecessary evaluation of x is made, because If has the HoldRest attribute:

myEchoQ = False;
Module[{}, x = Sqrt[2]; If[myEchoQ, Echo[x]]; N[x]]

When myEchoQ is set to True, an echo is generated:

myEchoQ = True;
Module[{}, x = Sqrt[2]; If[myEchoQ, Echo[x]]; N[x]]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract