3

Given a function with several arguments

func[a,b,g1[x],g1[x,y],g2[1],g2[g1[1]],3]

I would like to extract all arguments with the head g1 and g2 as a list. So the output I am looking for is

{g1[x],g1[x,y],g2[1],g2[g1[1]]}

The way I used to extract one head, say g1, is simply using the rule

/.func[l___,x__g1,r___]:> {x}

However, with two heads, this method does not work. I could write a module to do that but I wonder if there is a simpler way like the above rule for one head. Thank you so much!

mastrok
  • 591
  • 2
  • 9

2 Answers2

8

Either

takeHeads = Cases[#, _g1 | _g2] &;
func[a, b, g1[x], g1[x, y], g2[1], g2[g1[1]], 3] // takeHeads

{g1[x], g1[x, y], g2[1], g2[g1[1]]}

or define func itself as

func = Cases[{##}, _g1 | _g2] &;
func[a, b, g1[x], g1[x, y], g2[1], g2[g1[1]], 3]

{g1[x], g1[x, y], g2[1], g2[g1[1]]}

march
  • 23,399
  • 2
  • 44
  • 100
Coolwater
  • 20,257
  • 3
  • 35
  • 64
3
Select[{##&@@func[a,b,g1[x],g1[x,y],g2[1],g2[g1[1]],3]},h=#;Head@#==h&]&/@{g1,g2}    

{{g1[x], g1[x, y]}, {g2[1], g2[g1[1]]}}

ZaMoC
  • 6,697
  • 11
  • 31