# Find all instances of a function with a given head and replace their arguments

I'm trying to pattern-match all the functions with head Sin in list and replace their single input with a value.

Clear[a,x,y,z]
testList = {x, Sin[x], Sin[y],x^2*y, g[y,x], h[x,y,z], Cos[Tan[x]]}
testList /. f_Sin[a_] :> (f[a] /. a->10)


However, this is giving me

{x, Sin[x], Sin[y], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]}


Why? What am I doing wrong?

• why not just testList /. Sin[_] -> Sin?
– kglr
Dec 22, 2020 at 10:22
• try also testList /. _Sin -> Sin
– kglr
Dec 22, 2020 at 10:24
• consider testList2 = {x, Sin[x], Sin[y][t], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]}; testList2 /. f_Sin[a_] :> (f[a] /. a -> 10)
– kglr
Dec 22, 2020 at 10:46
• the pattern _Sin (and the pattern f_Sin) matches any expression with Head Sin, that is, expressions Sin[x] and Sin[y] in your testList. But the pattern _Sin[a_] is any expression with Head Sin evaluated at a single argument and there are no such expressions in your testList.
– kglr
Dec 22, 2020 at 10:58
• Btw, you can do testList /. (f : Sin)[a_] :> (f[a] /. a -> 10) to get the desired result.
– kglr
Dec 22, 2020 at 11:07

What kglr recommends is the best practice for what you want to do, but here is pattern that does it your way.

testList = {x, Sin[x], Sin[y], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]};
testList /. f : Sin[a_] :> (f /. a -> 10)

{x, Sin, Sin, x^2 y, g[y, x], h[x, y, z], Cos[Tan[x]]}


This works because it recognizes that f matches the whole expression Sin[...], so that writing f[a] in (f[a] /. a -> 10) is wrong.

This approach is not without it uses. Say you wanted pick out the expressions with the heads Sin and Cos. Then

testList /. f : (Sin | Cos)[a_] :> (f /. a -> 10)

{x, Sin, Sin, x^2 y, g[y, x], h[x, y, z], Cos}


is a reasonable solution.

Is this what you want?

testList /. Sin[a_] -> (f[a] /. a -> 10)

Hope this helps

• You have no reference to f before ->. Why should it work?
– Our
Dec 22, 2020 at 10:19
• And why mine doesn't work?
– Our
Dec 22, 2020 at 10:20
• and note that, this "answer" doesn't work
– Our
Dec 22, 2020 at 10:26
• May be I have misundestood how the final output should look like? Can you post the list how it should finally look like, please? Dec 22, 2020 at 10:33
• {{x, Sin, Sin, x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]}}
– Our
Dec 22, 2020 at 10:46

You want to choose all items with Sin head. And replace them with Sin

So you can try

{x, Sin[x], Sin[y], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]} /. x_Sin :> Sin


notice x_Sin , x is useless, so we can delete it

{x, Sin[x], Sin[y], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]} /. _Sin :> Sin


Another angle:

Choose all the items look like Sin[_] , replace _ with 10

{x, Sin[x], Sin[y], x^2*y, g[y, x], h[x, y, z], Cos[Tan[x]]} /. Sin[x_] :> Sin


the x in the Sin[x_] can be deleted.