Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to create a function something like this:

test[x_] := (Print[1]; Return[2];)

Except it prints 1 when executed as test[a] for any a on the notebook, but when used in computations uses the 2 value instead.

Thus test[2342] will output just 1 but test[43589] + 1 will output just 2 (because the value returned, 2, is used instead).

I have looked into Interpretation but that returns a held object and does not allow you do perform operations like test[1] + 123 without explicitly releasing the hold.

share|improve this question
test[1]+1 prints 1 and outputs 3 – eldo Jul 12 '14 at 18:46
@eldo I know. I only want it to output 3, and hide the 1. However, if you just call test[1] then I want it to print 1 and hide the 2 – 1110101001 Jul 12 '14 at 18:47
up vote 7 down vote accepted

Does this do what you're after?

test[a_] /; Length[Stack[]] == 3 := 1
test[a_] := 2

(* 1 *)

(* 2 *)

1 + test[134123]
(* 3 *)

The value return by Stack[] in the condition is in the first example

{test, Equal, Length}

In the second, it is

{Identity, test, Equal, Length}

One can see that if test is called by itself, the length of the stack will be three. If test appears inside other functions, the stack will be longer.

share|improve this answer
I seem to recall a similar question a few weeks ago, but I can't find it. Anyone? – Michael E2 Jul 12 '14 at 19:39
Yes! Just what I needed! – 1110101001 Jul 12 '14 at 20:40
+1 - there's a function not seen often! – ciao Jul 12 '14 at 20:49
@rasher Yes, and with good reason, I expect. Thanks for the upvote. – Michael E2 Jul 12 '14 at 20:54

Like this?

test[1] := Print[1]
test[x_] := Return[2]



test[2] + 1


share|improve this answer
I think I chose a bad example. In general just entering test[a] should give 1 but using test[a] in any computation should use the value 2 – 1110101001 Jul 12 '14 at 19:00
test[x_, code_] := If[code == 1, Print[1], 2]


share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.