Function Repository Resource:

When

Source Notebook

An operator form of Which

Contributed by: Taliesin Beynon

ResourceFunction["When"][test1,value1,test2,value2,][e]

evaluates each of the testi[e] in turn, returning the value of the valuei corresponding to the first test that yields True; otherwise, it yields e unchanged.

Details and Options

ResourceFunction["When"] must have at least one test and value.
ResourceFunction["When"] has attribute HoldRest.

Examples

Basic Examples (1) 

When evaluates the corresponding value only when the specified condition is met:

In[1]:=
ResourceFunction["When"][# < 3 &, Print["small"]][1]
In[2]:=
ResourceFunction["When"][# < 3 &, Print["small"]][5]
Out[2]=

Scope (2) 

Use a single test with When:

In[3]:=
ResourceFunction["When"][IntegerQ, "integer"][1]
Out[3]=
In[4]:=
ResourceFunction["When"][IntegerQ, "integer"][1.]
Out[4]=

Try several tests in turn:

In[5]:=
ResourceFunction["When"][# == 1 &, "one", # == 2 &, "two"][2]
Out[5]=
In[6]:=
ResourceFunction["When"][# == 1 &, "one", # == 2 &, "two"][3]
Out[6]=

Properties and Relations (2) 

Which takes a test expression whereas When takes a test function:

In[7]:=
a = 1; Which[a == 1, x]
Out[7]=
In[8]:=
ResourceFunction["When"][# == 1 &, x][1]
Out[8]=

You can think of When as an operator form of Which:

In[9]:=
ResourceFunction["When"][# == 1 &, x]
Out[9]=
In[10]:=
%[1]
Out[10]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 06 February 2019

Related Resources

License Information