2
$\begingroup$

I have a simple expression containing a Condition(s) like

a /; a > 1

I wish to separate the expression from the condition, to display like

| expr | cond  |
----------------
| a    | a > 1 |

How can I obtain the sub-expression a from the expression a /; a > 1? Attempting to remove the Conditions by Replace doesn't seem to work, probably because the Condition in the pattern is being interpreted at the top-level:

in = a /; a > 1

in /. Condition[expr_, cond_] :> expr
in /. HoldPattern[Condition[expr_, cond_]] :> expr
in /. Unevaluated[Condition[expr_, cond_]] :> expr
in /. Verbatim[Condition[expr_, cond_]] :> expr

These all output the unchanged input:

>>> a /; a > 1

Here's a hacky workaround:

in /. Condition -> dummy /. dummy[expr_,cond_] :> expr

What's the right way to do this?

$\endgroup$
5
  • 2
    $\begingroup$ try in /. Verbatim[Condition][expr_, cond_] :> expr? $\endgroup$
    – kglr
    Feb 17, 2021 at 11:50
  • $\begingroup$ and in /. HoldPattern[Condition][expr_, cond_] :> expr $\endgroup$
    – kglr
    Feb 17, 2021 at 11:52
  • $\begingroup$ @kglr aw yep, how clumsy of me, thanks! $\endgroup$
    – Anti Earth
    Feb 17, 2021 at 11:56
  • 1
    $\begingroup$ you can also use in /. Condition -> (# &) and in /. c_Condition :> First[c] $\endgroup$
    – kglr
    Feb 17, 2021 at 12:01
  • 2
    $\begingroup$ @kglr You could convert these comments into an answer. The only problem I have is with the version HoldPattern[Condition][expr_, cond_] - I think this is a misuse of HoldPattern, which is used where Verbatim should be used. $\endgroup$ Feb 17, 2021 at 12:27

1 Answer 1

4
$\begingroup$
in = a /; a > 1

Using Verbatim[Condition] instead of Condition gives the expected result

in /. Verbatim[Condition][expr_, cond_] :> expr
a

You can also use

in /. Condition -> (# &)

in /. c_Condition :> First[c]

The following also work

in /. (foo : Condition)[expr_, cond_] :> expr

in /. HoldPattern[Condition][expr_, cond_] :> expr

in /. PatternSequence[Condition][expr_, cond_] :> expr

in /. Alternatives[Condition][expr_, cond_] :> expr

The last three, as noted by Leonid in comments, are misuses of HoldPattern, PatternSequence, and Alternatives.

$\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.