# How to test a condition for a list and output all the expression that is true?

Suppose that I have a list

lis={x-y,x+y,x*y};


and a function

f[a_,b_]:=#/.{x->a,y->b}&


I want to output all the one in lis, such that f[2,2]==4, how to do this?

I try to do it by

Catch[If[f[2, 2] == 4, Throw[#] & /@ lis]]


but not work.

After a while, I figure it out that I can do this by

Catch[If[Evaluate[# /. {x -> 2, y -> 2}] == 4, Throw[#]] & /@ lis]


Then the problem is how the get all of the one satisfied? not just the first one.

• This looks like a job for 'Select'! – Aisamu Nov 26 '14 at 12:07
• It works for me:Select[lis, Evaluate[# /. {x -> 2, y -> 2}] == 4 &], did there any way to write the condition as a function? I mean, in the real case, I have a lot of condtion, such as #/.{x->2,y->1}==2 and so on... – van abel Nov 26 '14 at 12:17

Using the OP's function f

lis = {x - y, x + y, x*y};

f[a_, b_] := # /. {x -> a, y -> b} &

Map[First, Cases[Map[{#, f[2, 2][#]} &, lis], {_, 4}]]


{x + y, x y}

Alternatively

Reap[Map[If[f[2, 2][#] == 4, Sow[#]] &, lis]][[-1, 1]]


{x + y, x y}

• why the output is not clean when I delete [[-1,1]] in the alternatively code? – van abel Nov 26 '14 at 14:04
• The first part shows all the output from map. The sown values are in the last part. See Reap – Chris Degnen Nov 26 '14 at 14:09
• ok, it works any way. – van abel Nov 26 '14 at 14:13
list = {x - y, x + y, x*y};


Using a different test function, that tests for the equality and accepts the equality value as a parameter:

testFun[{a_, b_, c_}] := (# /. {x -> a, y -> b}) == c &;
testList = {{2, 2, 4}, {2, 0, 2}};
(* {2, 2, 4} means f[2,2] == 4, and {2, 0, 2} means f[2,0] == 2 *)


You can either Map over list, returning the elements that match any test provided:

Select[list, Or @@ Through[(testFun /@ testList)[#]] &]

(* {x - y, x + y, x y} *)


Or you can Map over testList, returning a the elements that matched each of the tests:

Function[{currTest}, Select[list, testFun@currTest]] /@ testList

(* {{x + y, x y}, {x - y, x + y}} *)

• why the output is not my expected? it should be x+y and x y – van abel Nov 26 '14 at 14:12
• You mentioned that on the real case you have a lot of conditions, so I've made a list of them -- testList. If you look at the last line of the answer, you will see that the first element is indeed {x + y, x y}, which corresponds to the first condition of testList, {2,2,4} (representing the test f[2,2] == 4). If you want to test more conditions, just add mode triples to testList, in the form {a,b,c} (representing f[a,b] == c) – Aisamu Nov 26 '14 at 17:04

You can use Select if you are willing to modify your function slightly:

Select[lis, (Function[{x, y}, #][2, 2] == 4) &]

(*{x + y, x y}*)