Function Repository Resource:

# SetUnless

Initialize a value unless it already satisfies a given condition

Contributed by: Richard Hennigan (Wolfram Research)
 ResourceFunction["SetUnless"][expr,val,test] evaluates expr = val if test[expr] does not return True. ResourceFunction["SetUnless"][val,test] represents an operator form of ResourceFunction["SetUnless"]. ResourceFunction["SetUnless"][test] represents an operator form of ResourceFunction["SetUnless"].

## Details and Options

In ResourceFunction["SetUnless"][expr,val,f], the value of expr will be set to val if f[expr] returns anything other than True.
The following forms are equivalent:
ResourceFunction["SetUnless"][expr,val,test]
ResourceFunction["SetUnless"][test][expr,val]
ResourceFunction["SetUnless"][val,test][expr]
ResourceFunction["SetUnless"][test][val][expr]
ResourceFunction["SetUnless"] has the attributes HoldFirst and SequenceHold.

## Examples

### Basic Examples

Initialize a symbol:

 In[1]:=
 Out[1]=

The value is not set if it already satisfies the given criteria:

 In[2]:=
 Out[2]=
 In[3]:=
 Out[3]=

The expr does not need to be a symbol:

 In[4]:=
 Out[4]=
 In[5]:=
 Out[5]=
 In[6]:=
 Out[6]=

Use the operator forms:

 In[7]:=
 Out[7]=
 In[8]:=
 Out[8]=
 In[9]:=
 Out[9]=
 In[10]:=
 Out[10]=
 In[11]:=
 Out[11]=
 In[12]:=
 Out[12]=
 In[13]:=
 Out[13]=
 In[14]:=
 Out[14]=
 In[15]:=
 Out[15]=

### Scope

Use Unevaluated to prevent evaluation of the second argument unless needed:

 In[16]:=
 Out[16]=
 In[17]:=
 Out[17]=
 In[18]:=
 Out[18]=

Without using Unevaluated, the second argument will evaluate, even if not being used:

 In[19]:=
 Out[19]=

Use an additional Unevaluated to get the same behavior as SetDelayed:

 In[20]:=
 In[21]:=
 Out[21]=

### Applications

Initialize a counter if it doesn’t already exist before incrementing:

 In[22]:=
 Out[21]=

If the counter ends up with an invalid value, Increment will no longer return an integer:

 In[23]:=
 Out[23]=
 In[24]:=
 Out[24]=

Use SetUnless to ensure a valid value before incrementing:

 In[25]:=
 Out[12]=

Create a function that stores data in an association and initializes it if necessary:

 In[26]:=
 In[27]:=
 Out[27]=
 In[28]:=
 Out[28]=

Check the data:

 In[29]:=
 Out[29]=

Clear the data:

 In[30]:=

Now save will reinitialize the association and start again:

 In[31]:=
 Out[31]=
 In[32]:=
 Out[32]=

Saving will reset the association if it is no longer valid:

 In[33]:=
 Out[33]=
 In[34]:=
 Out[34]=
 In[35]:=
 Out[35]=
 In[36]:=
 Out[36]=
 In[37]:=
 Out[37]=

### Properties and Relations

If test[expr] does not explicitly yield True, it will be considered False:

 In[38]:=
 Out[38]=
 In[39]:=
 Out[39]=

SetUnless has the SequenceHold attribute:

 In[40]:=
 Out[40]=
 In[41]:=
 Out[41]=

## Requirements

Wolfram Language 11.3 (March 2018) or above