Function Repository Resource:

EchoIf

Source Notebook

A curried form of Echo that can be useful in certain debugging situations

Contributed by: Paco Jain (Wolfram Research)

ResourceFunction["EchoIf"][cond][expr]

returns expr, also printing expr using HoldForm[expr] as the label if cond evaluates to True.

ResourceFunction["EchoIf"][cond,label][expr]

returns expr, also printing expr prepended with the given label if cond evaluates to True.

ResourceFunction["EchoIf"][cond,label,f][expr]

returns expr, also printing f[expr] prepended with the given label if cond evaluates to True.

Details and Options

ResourceFunction["EchoIf"] has attribute HoldFirst.
In its one-argument form, ResourceFunction["EchoIf"] uses HoldForm[expr] as the label that is passed to Echo.
If label is given the value Automatic, a held form of expr is used as a label.

Examples

Basic Examples (5) 

Conditionally echo an expression:

In[1]:=
ResourceFunction["EchoIf"][True][2 + 2]
Out[1]=
In[2]:=
ResourceFunction["EchoIf"][False][2 + 2]
Out[2]=

Conditionally echo an expression, specifying a non-default label:

In[3]:=
debug = True;
2 + 2 // ResourceFunction["EchoIf"][debug, "intermediate result 1:\n"]
Out[4]=

Conditionally echo an expression, specifying a non-default label and echoing function:

In[5]:=
debug = True;
myPrimes = Select[Range[100], PrimeQ] // ResourceFunction["EchoIf"][debug, "prime count:\n", Length]
Out[6]=

Conditionally echo an expression, specifying a non-default label and echoing function:

In[7]:=
debug = True;
myFunction[x_] := Sqrt[Factorial[x]]
myFunction[5] // ResourceFunction["EchoIf"][debug, "numeric result:\n", N]
Out[9]=

Conditionally echo an expression, specifying a non-default echoing function but automatic labeling:

In[10]:=
debug = True;
myPrimes = Select[Range[100], PrimeQ] // ResourceFunction["EchoIf"][debug, Automatic, Multicolumn[#, 5] &]
Out[11]=

Scope (1) 

Evaluating EchoIf[cond] without sub-arguments returns a Function expression, having attribute HoldFirst:

In[12]:=
ResourceFunction["EchoIf"][debug]
Out[12]=

Version History

  • 1.0.0 – 14 August 2019

License Information