3
$\begingroup$

For example of below Switch function.

In[]:= Module[{f},
 f[x_] := Switch[x, 1, 2, 3, 4];
 {f[1], f[3], f[x]}
 ]

Out[]= {2, 4, Switch[x,
  1, 2,
  3, 4]}

f[1] and f[3] is evaluated as defined, but since it doesn't define a default case, the original input seems to be a more natural result, and more friendly one.

Is it possible to define the above f[x] so the output becomes:

Out[]= {2, 4, f[x]}

I tried to use Unevaluated[f[x]], but it doesn't seem to work.

$\endgroup$
5
$\begingroup$
ClearAll[f, x]

Block[{f}, f[x_] := Switch[x, 1, 2, 3, 4, _, Defer[f][x]];
 {f[1], f[3], f[5], f[x]}]
{2, 4, f[5], f[x]}
| improve this answer | |
$\endgroup$
6
$\begingroup$
Block[{f}, 
 f[x_] := With[{res = Switch[x, 1, 2, 3, 4, _, $Failed]}, res /; res =!= $Failed];
 {f[1], f[3], f[x]}
]

(*{2, 4, f[x]}*)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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