4
$\begingroup$

Suppose i have a function

condition[pattern_,list_]:=With[
   {x=Unique["x"]},
   Condition[Pattern[Evaluate[x],pattern],Not@StringContainsQ[x,list]]
];

If i evaluate condition[_,{"a","b","c"}] i get an error.

But if i manually evaluate the right hand side i get the required result.

With[
   {x=Unique["x"]},
   Condition[Pattern[Evaluate[x],_],Not@StringContainsQ[x,{"a","b","c"}]]
]

result is

x56_ /; ! StringContainsQ[x56, {"a", "b", "c"}]
$\endgroup$
  • $\begingroup$ You could "isolate" Condition head by wrapping it with Identity: condition[pattern_, list_] := With[{x = Unique@"x"}, Identity[Condition][x : pattern, Not@StringContainsQ[x, list]]]. $\endgroup$ – jkuczm Aug 10 '18 at 9:32
  • $\begingroup$ In case of simple condition that just applies function to whole expression matched by pattern you could use PatternTest instead of Condition: condition[pattern_, list_] := pattern?(Not@*StringContainsQ[list]). $\endgroup$ – jkuczm Aug 10 '18 at 9:33
4
$\begingroup$

From the help for With:

You can use With[{vars},body/;cond] as the right-hand side of a transformation rule with a condition attached.

Basically, your code is that construction. Avoid having condition as the first head of the body of With:

condition[pattern_, list_] := 
  With[{x = Unique["x"]}, 
   Apply[Condition, {Pattern[x, pattern], 
     Not@StringContainsQ[x, list]}]];

condition[_, {"a", "b", "c"}]
(*x11_ /; ! StringContainsQ[x11, {"a", "b", "c"}]*)
$\endgroup$
  • 1
    $\begingroup$ You might want to prevent evaluation of Condition arguments by using holding wrapper instead of list: Condition @@ Hold[x : pattern, Not@StringContainsQ[x, list]] $\endgroup$ – jkuczm Aug 10 '18 at 9:28

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.