Find all heads a function is defined on

So say I've got a function g defined as follows:

g[x_Integer] := x + 1
g[s_String] := s <> "!!!"

How would I write a function GetHeads such that GetHeads[g] == {{Integer}, {String}} (i.e. the function returns the heads of all groups of arguments g is defined on)?

• You may start by (DownValues@g)[[All, 1, 1, 1]] – Dr. belisarius Sep 17 '14 at 18:11

If your definitions are exactly like you show, every time, you can use belisarius's method, slightly refined:

g[x_Integer] := x + 1
g[s_String] := s <> "!!!"

(DownValues@g)[[All, 1, 1, 1, 2, 1]]
{Integer, String}

However this is fragile in that it will fail if your definitions are different, e.g.:

g[r_ /; Head[r] === Real] := r + Pi

g[a_List?MatrixQ] := foo[a]

(DownValues@g)[[All, 1, 1, 1, 2, 1]]

Part::partd: Part specification {HoldPattern[g[x_Integer]]:>x+1,HoldPattern[g[s_String]]:>s<>!!!,HoldPattern[g[r_/;Head[<<1>>]===Real]]:>r+[Pi],HoldPattern[g[(a:Blank[<<1>>])?MatrixQ]]:>foo[a]}[[All,1,1,1,2,1]] is longer than depth of object. >>

If your intent is a truly robust method you may need to actually evaluate the function to see if it "accepts" the argument, meaning that it evaluates to something other than itself. If it is costly to run a full evaluation you can interrupt the process as soon as a rule match is found by using my step function from:

step @ g[#] & /@ {1, "a", 2.5, 1/2, I + 2, {}} // InputForm
{HoldForm[1 + 1], HoldForm[StringJoin["a", "!!!"]],
HoldForm[2.5 + Pi], g[1/2], g[2 + I], g[{}]}

Note that the types that match partially evaluate and are held by HoldForm, whereas the ones that do not match return with head g. You could therefore use something like:

SetAttributes[test, HoldFirst]

test[f_, expr_List] := If[MatchQ[step @ f[#], _HoldForm], Head@#, ## &[]] & /@ expr

Example:

test[g, {1, "a", 2.5, 1/2, I + 2, {}}]
{Integer, String, Real}

This returns the heads of the arbitrary expressions for which a match is found.

• Very nice and always thorough. +1 – RunnyKine Sep 17 '14 at 19:32

This also works:

getHeads[g_] := DownValues[g][[All, 1, 1, 1]] /. Verbatim[Pattern][_, k_] :> k[]

Then: