1
$\begingroup$

I have defined a function fun[f_[x_,y_]]. When I call it, I want to wrap everything by Unevaluated:

fun[Unevaluated[f][Unevaluated[x], Unevaluated[y]]

But the above expression looks clumsy, especially if the arguments of fun is more complicated. Is there a more elegant way to do it?

A simple example of the function fun is as follows. The last line is what I expect to get.

fun[f_[x_, y_]] := ToExpression[ToString[f] <> ToString[x] <> ToString[y]]
f = 1; x = 1; y = 1;
fun[f[x, y]]
(* -> 111 *)
fun[Unevaluated[f][Unevaluated[x], Unevaluated[y]]
(* -> fxy *)

I tried several ways by using a single Unevaluated or HoldPattern, and they do not work.

$\endgroup$
  • 1
    $\begingroup$ Have you tried giving fun the HoldAll attribute? $\endgroup$ – J. M. will be back soon Aug 14 '15 at 16:13
  • $\begingroup$ I just tried, and it does not work. $\endgroup$ – renphysics Aug 14 '15 at 16:21
  • 1
    $\begingroup$ @renphysics Why? SetAttributes[fun, HoldAll]; fun[f_[x_, y_]] := Unevaluated[f][Unevaluated[x], Unevaluated[y]]; f = x = y = 1; fun[f[x, y]] $\endgroup$ – Kuba Aug 14 '15 at 16:35
4
$\begingroup$

If I understand what you want:

SetAttributes[fun, HoldAll];
fun[expr_] := Identity @@ Identity @@ 
 MapAll[Unevaluated, Hold[expr], Heads -> True]

The two Identity operations fix the fact that MapAll applies Unevaluated to the entire expression as well - MapAll[g, f[x,y]] is g[g[f][g[x],g[y]] when we want g[f][g[x],g[y] - and remove the Hold we artificially put in.

$\endgroup$
  • $\begingroup$ +1 for the use of MapAll! $\endgroup$ – march Aug 14 '15 at 16:28

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.