5
$\begingroup$

So I have this function :

Sqrt[-1 + Tanh[#1 - #2]^2] &

How can I transform it into

f[x_,y_]=Sqrt[-1 + Tanh[x - y]^2] 

I tried

Sqrt[-1 + Tanh[#1 - #2]^2] &/. #1 -> x /. #2 -> y /. & -> 1

But apparently /. & -> 1 doesn't work

$\endgroup$
  • 1
    $\begingroup$ instead of using repeated /.s, use expr /. {x -> a, y -> b, z -> c} $\endgroup$ – user6014 Aug 3 at 23:33
13
$\begingroup$

Well, the easy way is to evaluate it for [x,y].

f[x_, y_] = Sqrt[-1 + Tanh[#1 - #2]^2] &[x, y];

If you'd rather do it with a replacement, you should understand the FullForm because that's what replacement works on.

Sqrt[-1 + Tanh[#1 - #2]^2] & // FullForm
(*
  Function[Sqrt[Plus[-1,Power[Tanh[Plus[Slot[1],Times[-1,Slot[2]]]],2]]]]
*)

So, you want to remove Function.

Sqrt[-1 + Tanh[#1 - #2]^2] & /. {Slot[1] -> x, Slot[2] -> y, Function -> Identity}
(*
  Sqrt[-1+Tanh[x-y]^2]
*)
$\endgroup$
13
$\begingroup$

I think the easiest way would be to define(name) the pure function f

f = Sqrt[-1 + Tanh[#1 - #2]^2] &

and use it accordingly

f[x,y] 
(*Sqrt[-1 + Tanh[x - y]^2]*)
$\endgroup$
2
$\begingroup$

Here's a general function, which I think protects the body of the Function from being evaluated:

def[Function[body_], f_] := 
 With[{nvar = Max@Cases[Hold[body], Slot[k_] :> k, Infinity]},
  With[{vars = Thread[
      ToExpression[
       Table["x" <> ToString@k, {k, nvar}],
       StandardForm, 
       Hold],
      Hold]},
   vars /. Hold[v_] :> Block[v,
      Hold[SetDelayed][
        Hold[f] @@ (Pattern[#, Blank[]] & /@ v),
        Hold[body] /. Slot[k_] :> RuleCondition[v[[k]]]
        ] // ReleaseHold
      ]
   ]]

Example:

ClearAll[fff];
xx = 2; x1 = 4;
def[xx + #2 - #1^2 &, fff]

DownValues@fff
(*  {HoldPattern[fff[x1_, x2_]] :> xx + x2 - x1^2}  *)

OP's:

def[Sqrt[-1 + Tanh[#1 - #2]^2] &, f]
DownValues@f
(*  {HoldPattern[f[x1_, x2_]] :> Sqrt[-1 + Tanh[x1 - x2]^2]}  *)
$\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.