Function Repository Resource:

HeadQ

Source Notebook

Check if expressions have certain heads

Contributed by: Jesse Friedman and Michael Sollami

ResourceFunction["HeadQ"][expr,head]

gives True if the head of expr is head, and False otherwise.

ResourceFunction["HeadQ"][expr,head1|head2 |]

gives True if the head of expr is any of the alteratives headi and False otherwise.

ResourceFunction["HeadQ"][heads]

is an operator form of ResourceFunction["HeadQ"].

Details and Options

To check the heads of expressions before any evaluation, use Unevaluated on expr.
ResourceFunction["HeadQ"] assumes that evaluating an atomic expression is safe from side effects.

Examples

Basic Examples (5) 

Test if an expression has a certain head:

In[1]:=
ResourceFunction["HeadQ"]["hello", String]
Out[1]=

Test for heads using the operator form:

In[2]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/79375da4-282e-477c-8260-505aba0e4826"]
Out[2]=

Check for multiple heads with Alternatives:

In[3]:=
ResourceFunction["HeadQ"][List | Integer] /@ {{1}, 2, <|3 -> 3|>}
Out[3]=

Check the heads of any type of expression:

In[4]:=
TextGrid[{"HeadQ"[##], ResourceFunction["HeadQ"][##]} & @@@ {{Cell["1", "Text"], Cell}, {Association["a" -> 1, "b" -> 2], Association}, {SparseArray[Automatic, {2, 2}, 0, {1, {{0, 1, 2}, {{1}, {2}}}, {1, 1}}], SparseArray}, {QuantityArray[{10, 30}, "Meters"], QuantityArray}},
  Dividers -> Gray, Spacings -> {1, 1}]
Out[4]=

Check heads while holding expressions:

In[5]:=
ResourceFunction["HeadQ"][Plus][Unevaluated[1 + 2 + 3]]
Out[5]=

By default HeadQ does not prevent evaluation:

In[6]:=
ResourceFunction["HeadQ"][#][1 + 2 + 3] & /@ {Plus, Integer}
Out[6]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 23 April 2020

Related Resources

License Information