0
$\begingroup$

I need to store or use a matched pattern, as I need it later on. I'd like it so that the match is NOT confined in a pattern-like syntax like:

pattern /; test
lhs :> rhs /; test
lhs := rhs /; test

or

pattern ? test 

So I've been using this:

MatchQ[expr, x:pattern /; (var = x; True)]

Is there a neater way to do it, like:

var = MatchQ[expr, x:pattern extracode]
$\endgroup$
3
  • $\begingroup$ I suspect that you meant var==x. Could you provide a simple example of some inputs and the desired outputs? $\endgroup$ Commented Nov 5, 2016 at 23:36
  • $\begingroup$ I then use var. If I want a return mechanism in a function (which has a Block or Module inside), I return var. $\endgroup$
    – kozner
    Commented Nov 6, 2016 at 2:03
  • 2
    $\begingroup$ Would Cases perhaps do what you have in mind? $\endgroup$ Commented Nov 6, 2016 at 19:29

1 Answer 1

4
$\begingroup$

It is difficult to discern from your question what you're actually trying to do. Daniel mentioned Cases, and maybe you could use that. If not you could use a utility function in a PatternTest like this:

set = (var = #; True) &;

MatchQ[{1, 2, 3}, (x : _List)?set]

var
True

{1, 2, 3}

This particular pattern could also be written concisely as x_List?set.

Also consider Sow and Reap:

sow = (Sow@#; True) &;

MatchQ[{1, 2, 3}, (x : _List)?sow] // Reap
{True, {{{1, 2, 3}}}}
$\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.