Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

If I have a list of conditions:

{cond1,cond2,cond3}

and I want to use an If[] statement to test the intersection of these conditions (or, more generally, any subset of them, but let's start with the basic case first):

If[cond1&&cond2&&cond3,a,b]

How would I do that?

share|improve this question
2  
Something like conds = {cond1, cond2, cond3}; If[And @@ conds, a, b]? –  J. M. Oct 6 '12 at 13:23
    
Yes. Thanks J.M. I feel like I'm asking lots of quite trivial questions, but I have yet to get a feel for the syntax, and haven't got a good idea yet of what I need to search for in the documentation to find what I need. –  Ooku Oct 6 '12 at 13:33
add comment

1 Answer

up vote 5 down vote accepted

Don't worry about whether these are trivial questions: they are good opportunities to explain a little more about Mathematica's syntax.

The first point is that what you already had works fine. You can confirm this using FullForm.

If[cond1 && cond2 && cond3, a, b] // FullForm
(*If[And[cond1,cond2,cond3],a,b]*)

If you preferred, you could type out the And construction explicitly.

J.M.'s comment invokes the Apply function to change the Head of a List of things, in this case the conditions, to And.

And @@ {cond1, cond2, cond3} // FullForm
(* And[cond1,cond2,cond3] *)

Or equivalently

FullForm[Apply[And, {cond1, cond2, cond3}]]
(* And[cond1,cond2,cond3] *)

The FullForm is just for explication; you wouldn't use it in normal operations. So the short syntax for the above is:

And @@ {cond1, cond2, cond3}
(* cond1&&cond2&&cond3 *)

The usefulness of storing your list of conditions as a list is that it is then easier to use various other list-manipulation techniques to get those subsets of conditions mentioned in your question.

And @@ (Most@{cond1, cond2, cond3})
(* cond1&&cond2 *)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.