Wolfram Research

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

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

Examples

Basic Examples

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

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

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

Resource History

See Also

License Information