2
$\begingroup$

My purpose is to use a boolean expression as a requirement that a pattern must comply. The requirement is c1 == "a", and I am using it to select a string from a list:

Select[{"abc","def"},StringMatchQ[#, 
   StartOfString ~~ c1_~~__~~EndOfString /; 
    c1 == "a"] &]

However I want to specify that condition to be satisfied through a variable var that I can assign the expression that I may need:

Select[{"abc","def"},StringMatchQ[#, 
       StartOfString ~~ c1_~~__~~EndOfString /; 
        var] &]

However doing var = c1==a does not do the job. Is there a way to just store that expression, maybe in some other type of variable? My ultimate aim is to create a list of such variables, with several conditions in each entry to be satisfied when a determined entry be selected at different steps within a do loop.

$\endgroup$
4
$\begingroup$

You can use a pure function to store the boolean expression:

var = # == "a" &;

You can use it with PatternTest

Select[{"abc", "def"}, 
 StringMatchQ[StartOfString ~~ c1_?var ~~ __ ~~ EndOfString]]

{"abc"}

or with Condition:

Select[{"abc", "def"}, 
 StringMatchQ[StartOfString ~~ c1_ ~~ __ ~~ EndOfString /; var[c1]]]

{"abc"}

| improve this answer | |
$\endgroup$
  • $\begingroup$ Is this solution also suitable for lists? For example, list = {#1=="a", #2=="b"}& to then use it with its corresponding arguments,list[c1,c2]? Or would it be necessary to make individual pure functions list = {#=="a"&, #=="b"&}, what would make it much more inconvenient to specify its arguments in PatternTest or Condition? This latter case wouldn't allow me to use it in my intended purpose $\endgroup$ – abcd Jan 26 at 1:35
  • 1
    $\begingroup$ @abcd, with list = {#1=="a", #2=="b"}& the function call list[c1,c2] with return a list ({True, True}, {False, True} ... etc) . The predicate in Condition or PatternTest to evaluate to True or False. So, if you define list as, for example, ` list =And[#1=="a", #2=="b"]&` or as list = Or[#1=="a", #2=="b"]& it should work. $\endgroup$ – kglr Jan 26 at 3:26

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.