# order of evaluation defining a function

I'm quite sure this is an easy question but Im missing something.

I wish to define a function whose action depends on whether the input is a single matrix or a multiplication of two, For example:

I would want to do get:

f[x*y]
(* x+y *)

f[x]
(* x *)


Even though this example isn't interesting it is enough to demonstrate my issue.

I tried:

f[x_] := If[Head[Unevaluated[x]] == Times,
(Unevaluated[x][]) + (Unevaluated[x][])
,
x]


Indeed I get:

f[x*y]==x+y
(* True*)


But I get:

f[x]
(* If[Symbol == Times, Unevaluated[x][] + Unevaluated[x][], x] *)
f
(* If[Integer == Times, Unevaluated[] + Unevaluated[], 7] *)


Any explanation or an explanation of a better way to achieve my goal are welcome

• See HoldAll and friends.
– Kuba
Aug 22, 2017 at 14:14
• SetAttributes[f, HoldFirst]? Aug 22, 2017 at 14:14
• This doesn't help, tried it. Apparently the problem lies with the comparison Symbol==Times, and Integer==Times which for some reason doesn't evaluate to False. Aug 22, 2017 at 14:34
• You should use SameQ (or === for short) when comparing e.g. Heads. This ensures that the comparison is always evaluated to True or False, and not left unevaluated Aug 22, 2017 at 14:43

### Note

This answer explains why the problem in the question happens and how to solve it without changing the approach. Alucard's answer shows how to solve the problem with a more "Mathematica like" approach using SetDelayed with different patterns.

A bit of an explanation of what I already said in the comments:

If you look at the output for f[x], you'll see that Symbol == Times has not been replaced by False. For this reason, the If expression is returned unevaluated.

This happens because Symbol andTimes don't have a value (although they are "known" symbols, they're treated as unknown variables for the sake of comparison since there are no OwnValues).

To always get either True or False, you can use SameQ (=== for short):

In:=  Symbol === Times
Out:= False


you can use pattern matching

f[x_*y_] := x+y
f[x_] := x


examples:

f[2*3]
f[x]
f[x*y]
f


gives you

 5
x
x + y
5