4
$\begingroup$

Why condition /; not work inside pure function?
Suppose we have:

g[x_, y_] := x /; y > 0;
g[1, 3] -> 1
g[1, -3] -> g[1, -3]

I need a pure function with the same behavior. I thought it was a syntax error, but none of it works:

g1 = (#1 /; #2 > 0) &;
g2 = #1 /; #2 > 0 &;
g3 = #1 /; (#2 > 0) &;

Expected:

g1[1, 3] -> 1
g1[1, -3] -> g1[1, -3]
$\endgroup$
11
  • 2
    $\begingroup$ These work fine: 2 /. g1[x_, x - 2] :> 2 x and 1 /. g1[x_, x - 2] :> 2 x -- What do you expect to happen? $\endgroup$
    – Michael E2
    May 25, 2023 at 4:46
  • 1
    $\begingroup$ Condition creates a pattern. It does not evaluate to something else. It operates semantically only in situations where patterns are applied, such as ReplaceAll + Rule, Cases, Set / SetDelayed. Function does not apply patterns. $\endgroup$
    – Michael E2
    May 25, 2023 at 4:57
  • 2
    $\begingroup$ Note there are three different meanings of Condition in the docs. x /; y > 0 is the first kind. Something like g4[x_, y_] := x /; y > 0, which I assume you're talking about, is the third kind. It creates a rule of the second kind stored in DownValues[g4]. There's a further meaning described in the "Details" section. -- FWIW, I've wished for, as have others, a way to make Function application conditional in the way you seek. If you look into it deep enough, you realize that Function does not work the way a pattern-based rewrite rule like g4[x_, y_] :=... does. $\endgroup$
    – Michael E2
    May 25, 2023 at 5:07
  • 1
    $\begingroup$ I get it. Good luck :) $\endgroup$
    – Michael E2
    May 25, 2023 at 5:24
  • 2
    $\begingroup$ Maybe you could use this hack: g = {#1, #2} /. {x_, y_} :> x /; y > 0 & $\endgroup$
    – Sâu
    May 25, 2023 at 7:58

1 Answer 1

4
$\begingroup$

As supplement of @MichaelE2's comment. Condition is bit of "meta" in the sense that it will only be absorbed by specific functions with pattern matching features. And the order of evaluation also matters.

Similar to Condition, RuleCondition can partially satisfy your requirement.

RuleCondition[#1,#2>0]&[1,1]
(*1*)
RuleCondition[#1,#2>0]&[1,-1]
(*Fail*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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