Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The imperative if in programming is different from the logical if. But it isn't disconnected from logic.

In fact, it is closely related to the logical and: it is and with short-circuiting, enabling the left expression to control effects in the right.

In Lisp, the two-form if, namely (if x y), can be replaced by (and x y), because and has the right logic and result value, and also the short-circuiting semantics that y is not evaluated if x is false.

If we want the logical if, we can use the equivalent expression (or (not x) y), which has the same truth table:

     x     y  | (if x y)  |  (or (not x) y)
  ------------+-----------+----------------
   nil   nil  |    nil    |     t
   nil     t  |    nil    |     t
     t   nil  |    nil    |   nil
     t     t  |      t    |     t

The if/and relationship of course shows up in other languages:

   if (pointer != NULL) {
      if (pointer->foo == 42)
        do();
   }
-->

  if (pointer != NULL && pointer->foo)
    do();


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: