# Function that prints a different value than it returns

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.

-
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

Does this do what you're after?

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

test[134123]
(* 1 *)

Identity[test[134123]]
(* 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.

-
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?

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

test[1]


1

test[2] + 1


3

-
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]

test[anything,1]
(*1*)

test[anything,2]
(*2*)

-