Wolfram Research

Function Repository Resource:

AllSameBy

Source Notebook

Check if all the elements of a list give the same value after applying a function

Contributed by: Sander Huisman

ResourceFunction["AllSameBy"][list,f]

gives True when all elements of the list returns the same value when f is applied, and False otherwise.

Details

ResourceFunction["AllSameBy"] applies f sequentially from the first element to the last, until the result is different from the ones before; i.e., it short-circuits whenever possible.
When list has length 0 or 1, True is automatically returned, without f being applied.

Examples

Basic Examples (1) 

Test whether all numbers have the same parity:

In[1]:=
ResourceFunction["AllSameBy"][{1, 3, 7, 5}, Mod[#, 2] &]
Out[1]=

Scope (1) 

Test if all the numbers have the same magnitude:

In[2]:=
ResourceFunction["AllSameBy"][{-5, 5, 3 + 4 I}, Abs]
Out[2]=

Applications (1) 

Check if numbers are all prime or all composite:

In[3]:=
ResourceFunction["AllSameBy"][{3, 5, 7, 8, 13}, PrimeQ]
Out[3]=

Properties and Relations (4) 

AllSameBy can be implemented by applying f to all elements and then checking whether the results are all the same:

In[4]:=
list = {-5, 5, 5, 3 + 4 I, -3 - 4 I, 4, -4 + 3 I, 5 I, -5, 5};
Apply[SameQ][Map[Abs][list]]
Out[4]=

Compare with the original function:

In[5]:=
ResourceFunction["AllSameBy"][list, Abs]
Out[5]=

The difference becomes apparent when there are side effects:

In[6]:=
list = {-5, 5, 5, 3 + 4 I, -3 - 4 I, 4, -4 + 3 I, 5 I, -5, 5};
Apply[SameQ][Map[Echo /* Abs][list]]
Out[6]=

Compared to the original function, the last items are untouched:

In[7]:=
ResourceFunction["AllSameBy"][list, Echo /* Abs]
Out[7]=

Resource History

Related Resources

License Information