0
$\begingroup$

Consider a data list data, and a rule list rule. I want to select from data all elements that are in rule. For example, with

data = {a, a + 1, b, b + 2, c, c + 3, a + d, a + c, b + c};
rule = {a, d};

I want to select from data all elements that contains a or d. My solution is to invert the result from FreeQ, go through the rule list, and the pick out the results, like this:

HasQL[expr_, lst_] := 
 AnyTrue[Table[Not[FreeQ[expr, lst[[i]]]], {i, 1, Length[lst]}], 
  TrueQ]

and then Select[data, HasQL[#, rule] &] returns the expected result:

{a, 1 + a, a + d, a + c}

I tried cleaning up the code above:

HasQL[d_, r_] := AnyTrue[(!FreeQ[d, #]) & /@ r, TrueQ]
Select[data, HasQL[#, rule] &]

Is there a more elegant/clean way to achieve the same result?

$\endgroup$
  • 2
    $\begingroup$ Select[data, ! FreeQ[#, Alternatives @@ rule] &]? $\endgroup$ – J. M. will be back soon Mar 6 '18 at 3:26
  • $\begingroup$ @J.M. Nice. Thanks a lot! $\endgroup$ – egwene sedai Mar 6 '18 at 3:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.