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][[1]]) + (Unevaluated[x][[2]])
,
x]
Indeed I get:
f[x*y]==x+y
(* True*)
But I get:
f[x]
(* If[Symbol == Times, Unevaluated[x][[1]] + Unevaluated[x][[2]], x] *)
f[7]
(* If[Integer == Times, Unevaluated[7][[1]] + Unevaluated[7][[2]], 7] *)
Any explanation or an explanation of a better way to achieve my goal are welcome
HoldAll
and friends. $\endgroup$SetAttributes[f, HoldFirst]
? $\endgroup$Symbol==Times
, andInteger==Times
which for some reason doesn't evaluate toFalse
. $\endgroup$SameQ
(or===
for short) when comparing e.g. Heads. This ensures that the comparison is always evaluated toTrue
orFalse
, and not left unevaluated $\endgroup$