Short-circuiting boolean expressions

There is a term used in other languages to describe the behavior of compiled code which evaluates boolean expressions: short circuiting. Basically, it means that if a term in an expression determines its value, then following terms never get evaluated, since they are irrelevant. For example, I have noticed that this always works in AppleScript:
if class of x is not integer or x > 32 then . . . .
But this will throw an exception if x is something that can’t be coerced into a number:
if x > 32 or class of x is not integer then . . . .
It looks to me that the reason the first always works is that Applescript is short-circuiting, and therefore there is no attempt to evaluate the inequality if x is of inappropriate class.
Does anyone know if Applescript’s behavior is sufficiently well defined that I can be confident it will always short circuit? I know I can avoid the issue by breaking such expressions into separate, nested, if statements. If there is no such assurance that is what I will probably make a habit of doing. But I thought I'd ask if this is really necessary.

Hello
Short-circuiting is well-defined in AppleScript.
cf. ASLG > Operator References (p.179 of ASLG pdf)
http://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/Appl eScriptLangGuide/AppleScriptLanguageGuide.pdf
Regards,
H

Similar Messages

  • Pl/sql boolean expression short circuit behavior and the 10g optimizer

    Oracle documents that a PL/SQL IF condition such as
    IF p OR q
    will always short circuit if p is TRUE. The documents confirm that this is also true for CASE and for COALESCE and DECODE (although DECODE is not available in PL/SQL).
    Charles Wetherell, in his paper "Freedom, Order and PL/SQL Optimization," (available on OTN) says that "For most operators, operands may be evaluated in any order. There are some operators (OR, AND, IN, CASE, and so on) which enforce some order of evaluation on their operands."
    My questions:
    (1) In his list of "operators that enforce some order of evaluation," what does "and so on" include?
    (2) Is short circuit evaluation ALWAYS used with Boolean expressions in PL/SQL, even when they the expression is outside one of these statements? For example:
    boolvariable := p OR q;
    Or:
    CALL foo(p or q);

    This is a very interesting paper. To attempt to answer your questions:-
    1) I suppose BETWEEN would be included in the "and so on" list.
    2) I've tried to come up with a reasonably simple means of investigating this below. What I'm attempting to do it to run a series of evaluations and record everything that is evaluated. To do this, I have a simple package (PKG) that has two functions (F1 and F2), both returning a constant (0 and 1, respectively). These functions are "naughty" in that they write the fact they have been called to a table (T). First the simple code.
    SQL> CREATE TABLE t( c1 VARCHAR2(30), c2 VARCHAR2(30) );
    Table created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE pkg AS
      2     FUNCTION f1( p IN VARCHAR2 ) RETURN NUMBER;
      3     FUNCTION f2( p IN VARCHAR2 ) RETURN NUMBER;
      4  END pkg;
      5  /
    Package created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE BODY pkg AS
      2 
      3     PROCEDURE ins( p1 IN VARCHAR2, p2 IN VARCHAR2 ) IS
      4        PRAGMA autonomous_transaction;
      5     BEGIN
      6        INSERT INTO t( c1, c2 ) VALUES( p1, p2 );
      7        COMMIT;
      8     END ins;
      9 
    10     FUNCTION f1( p IN VARCHAR2 ) RETURN NUMBER IS
    11     BEGIN
    12        ins( p, 'F1' );
    13        RETURN 0;
    14     END f1;
    15 
    16     FUNCTION f2( p IN VARCHAR2 ) RETURN NUMBER IS
    17     BEGIN
    18        ins( p, 'F2' );
    19        RETURN 1;
    20     END f2;
    21 
    22  END pkg;
    23  /
    Package body created.Now to demonstrate how CASE and COALESCE short-circuits further evaluations whereas NVL doesn't, we can run a simple SQL statement and look at what we recorded in T after.
    SQL> SELECT SUM(
      2           CASE
      3              WHEN pkg.f1('CASE') = 0
      4              OR   pkg.f2('CASE') = 1
      5              THEN 0
      6              ELSE 1
      7           END
      8           ) AS just_a_number_1
      9  ,      SUM(
    10           NVL( pkg.f1('NVL'), pkg.f2('NVL') )
    11           ) AS just_a_number_2
    12  ,      SUM(
    13           COALESCE(
    14             pkg.f1('COALESCE'),
    15             pkg.f2('COALESCE'))
    16           ) AS just_a_number_3
    17  FROM    user_objects;
    JUST_A_NUMBER_1 JUST_A_NUMBER_2 JUST_A_NUMBER_3
                  0               0               0
    SQL>
    SQL> SELECT c1, c2, count(*)
      2  FROM   t
      3  GROUP  BY
      4         c1, c2;
    C1                             C2                               COUNT(*)
    NVL                            F1                                     41
    NVL                            F2                                     41
    CASE                           F1                                     41
    COALESCE                       F1                                     41We can see that NVL executes both functions even though the first parameter (F1) is never NULL. To see what happens in PL/SQL, I set up the following procedure. In 100 iterations of a loop, this will test both of your queries ( 1) IF ..OR.. and 2) bool := (... OR ...) ).
    SQL> CREATE OR REPLACE PROCEDURE bool_order ( rc OUT SYS_REFCURSOR ) AS
      2 
      3     PROCEDURE take_a_bool( b IN BOOLEAN ) IS
      4     BEGIN
      5        NULL;
      6     END take_a_bool;
      7 
      8  BEGIN
      9 
    10     FOR i IN 1 .. 100 LOOP
    11 
    12        IF pkg.f1('ANON_LOOP') = 0
    13        OR pkg.f2('ANON_LOOP') = 1
    14        THEN
    15           take_a_bool(
    16              pkg.f1('TAKE_A_BOOL') = 0 OR pkg.f2('TAKE_A_BOOL') = 1
    17              );
    18        END IF;
    19 
    20     END LOOP;
    21 
    22     OPEN rc FOR SELECT c1, c2, COUNT(*) AS c3
    23                 FROM   t
    24                 GROUP  BY
    25                        c1, c2;
    26 
    27  END bool_order;
    28  /
    Procedure created.Now to test it...
    SQL> TRUNCATE TABLE t;
    Table truncated.
    SQL>
    SQL> var rc refcursor;
    SQL> set autoprint on
    SQL>
    SQL> exec bool_order(:rc);
    PL/SQL procedure successfully completed.
    C1                             C2                                     C3
    ANON_LOOP                      F1                                    100
    TAKE_A_BOOL                    F1                                    100
    SQL> ALTER SESSION SET PLSQL_OPTIMIZE_LEVEL=0;
    Session altered.
    SQL> exec bool_order(:rc);
    PL/SQL procedure successfully completed.
    C1                             C2                                     C3
    ANON_LOOP                      F1                                    200
    TAKE_A_BOOL                    F1                                    200The above shows that the short-circuiting occurs as documented, under the maximum and minimum optimisation levels ( 10g-specific ). The F2 function is never called. What we have NOT seen, however, is PL/SQL exploiting the freedom to re-order these expressions, presumably because on such a simple example, there is no clear benefit to doing so. And I can verify that switching the order of the calls to F1 and F2 around yields the results in favour of F2 as expected.
    Regards
    Adrian

  • Airport Express short circuit A1264

    Hi,
    The Airport Express model A1264 at my inlaws stopped working all of a sudden last year, for now apparent reason. They bought newer version, but I kept the old one. Cleaning my closet and pondering to throw it away, I decided to take it apart. To my surprise I discovered burn-marks of a apparent short-circuit.
    Anybody else had this experience and should I report this?
    Thanx.

    The power supply inside the AirPort Express failed....a somewhart normal occurence if the Express has been in use for several years. I rarely got more than 3 years use out of the older version of the AiPort Express. Some users do better, some worse.
    The newer version of the Express....introduced about a year ago....runs much cooler, so hopefully it will have a longer average life than the older versions.

  • Boolean expression examples

    hey peeps, i was stuck with the following questions out of my text book the other day and i just asked my friend for some tips (here are the questions)
    q1) write an expression using boolean var a and b that equate to true when a and b are both trur and false
    q2)write an expression using boolean var a and b that evaluates true when only one of a and b is true and which is false if a and b are both flase or both true ( this is called exclusive or)
    q3) consider the expression (a && b) write an equivelant expression, one that evaluates to true at exactly the same values for a and b without using the && operator
    however, he gave me the answers <good you may think> but that now means i havent learnt anything and i was hoping someone could either set me a couple of similar questions or point me in the direction of a tutorial? I didnt want to ask him again as i dont want to bother him any more
    thanks very much

    Relational and boolean Operators
    Java has the full complement of relational operators. To test for equality you use a double equal sign, ==. For example, the value of
    <address>3 == 7</address>
    is false.
    Use a != for inequality. For example, the value of
    3 != 7
    is true.
    Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal) operators.
    Java, following C++, uses && for the logical "and" operator and || for the logical "or" operator. As you can easily remember from the != operator, the exclamation point ! is the logical negation operator. The && and || operators are evaluated in "short circuit" fashion. This means that when you have an expression like:
    A && Bonce the truth value of the expression A has been determined to be false, the value for the expression B is not calculated. For example, in the expression
    x != 0 && 1 / x > x + y // no division by 0the second part is never evaluated if x equals zero. Thus, 1 / x is not computed if x is zero, and no divide-by-zero error can occur.
    Similarly, if A evaluates to be true, then the value of A || B is automatically true, without evaluating B.
    Finally, Java supports the ternary ?: operator that is occasionally useful. The expression
    condition ? e1 : e2
    evaluates to e1 if the condition is true, to e2 otherwise. For example,
    x < y ? x : ygives the smaller of x and y.
    h3. from:+Core Java&trade; 2: Volume I&ndash;Fundamentals+
    By Cay S. Horstmann, Gary  Cornell
    Publisher : Prentice Hall PTR
    Pub Date : December 01, 2000
    ISBN : 0-13-089468-0
    Pages : 832
    chapter 3

  • Does ABSL (ByD Script) support Short Circuit Evaluation?

    Hi,
    short question:
    Does ABSL (ByD Script) support Short Circuit Evaluation?
    For example the following code snippet:
    var Call_query;
    Call_query = !this.LastChangeIdentity.IsSet() || (this.LastChangeIdentity.UUID.Content != CurrentIdentityUUID.Content);
    Will "this.LastChangeIdentity.UUID.Content" be evaluated and cause me into trouble if not initialized?
    PS: Is there a language specification available?

    I found something, which looks like a specification.
    See within the Business Center Wiki -> ByD Studio -> Best Practices for Implementation,
    section 'Best Practice for Business Object definition and scripting',
    download ' Syntax for Actions and Events.pdf'.
    Within this PDF, see section 'Logical Expressions'.
    Cite: The logical u201Candu201D (&&) and u201Coru201C (||) operators always evaluate the overall expression to a boolean value (u201Ctrueu201D or u201Cfalseu201D)
    This sounds to me, that Short Circuit Evaluation is not supported.
    BUT: There is no version number nor time stamp nor something else, which points out the status of this document.
    Can someone (from SAP) verify this?

  • IF operator as short-circuit not working in SSRS

    I have used IF operator as short circuit, like IF(expression, arg1, arg2) and this works in SSRS report when I do preview the report in visual studio 2012 however when I try to upload it on Report Server 2008 it gives me below error 
    "There is an error on line 109 of custom code: [BC30201] Expression expected. (rsCompilerErrorInCode)"
    Thanks,
    Tushar.

    Hi Tushar,
    After testing the issue in my local environment, I can reproduce the error message. In my scenario, the error is caused by using “==” instead of “=” in if…then…else statement. For more details, please see:
    Dim Shared Amount As Integer
    Public Function GetAmount( Type as String)
    If Type =="1" Then
    Amount=1
    Else
    Amount=2
    End If
    Return Amount
    End Function
    To fix this issue, could you please check if the if…then…else statement is used correctly? If the issue is still existed, please post the custom code.
    The following document about if…then…else statement in Visual Basic is for your reference:
    http://msdn.microsoft.com/en-us/library/752y8abs.aspx
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Boolean Expression Evaluator

    Hello everyone...
    Does any one know how to create a Java program that will evaluate boolean expression... For example, the user may enter (T AND T) OR F statement and the program will check the expression is valid or not and in addition it gives the answer T for true. Does anyone know where to download the free sample code that will be able to help me.. thanks.
    URGENT!
    -Eugene-

    http://www.japisoft.com/formula
    Features :
    * Decimal, string, boolean operators (or, and, not, xor...)
    * Unicode
    * Boolean expression support : (A or B) and not ( C equals D )
    * String expression support : "abc" != "cba"
    * IF THEN ELSE expression
    * Short expression format : 2x+3y
    * Variable : A=(cos(PI + x )*2) + [y-x]^2
    * Multiple lines expression : A = 1 B = A + 1 ...
    * Functions with decimal, boolean or string arguments
    * Evaluation tree produced by a pluggable parsing system
    * Evaluation optimization for symbol value changes
    * Standard library with 24 mathematical functions
    * Delegate for resolving unknown functions or symbols
    * Extend or add a new library dynamically
    * Share multiple formula context
    * Override any functions from the current library by your one
    * Support for multithreaded computing
    * Many samples (library extension, graphes) for API interesting parts
    * JDK 1.1 compliant (tested on JDK1.1.8 and JDK1.4.2)
    Best regards,
    A.Brillant

  • Short Circuit AND question (code included)

    I have a quick question about the short circuit AND operator...
    public class prac1 {
         public static final int aNumber = 19;
         public int age = 53;
         public static void main(String args[]) {
              if ((aNumber == 18) && (aNumber != 10)) {
                   System.out.println("You got it!");
    }You see I learned that Short Circuit AND means the first expression is evaluated and if it's false the 'code' is executed...
    So here is what I am understanding: if((aNumber == 18) already evaluates to false, right, but then I see it as && sees that it's false, but then shouldn't the code execute?
    Most likely the case: if((aNumber == 18) already evaluates to false, and because && only evaluates false expressions, and therefore since it's false the code doesn't execute... Am I correct?
    Just trying to get the && and || down... Thanks!
    Edited by: JavaPWNZ on Jul 2, 2008 5:58 AM

    sc3sc3 wrote:
    PhHein wrote:
    Hi,
    a bit confusing, but sort of yes. The && evaluates the first part ((aNumber == 18)) if that is false the following condition is not evaluated any more bacause the whole statement is false.
    Try this: String s = null;
    if(s != null && s.length() > 0){
    System.out.println("Here");
    }now try:
    String s = null;
    if(s != null & s.length() > 0){
    System.out.println("Here");
    nullpointer :-)As intended :)

  • IMac to tv with hdmi short circuit

    I have my iMac (Intel) connected to my Sony tv with an hdmi adapter.  It works fine except that sometimes the iMac seems to short circuit and turn off.  I read once that my cable may not be appropriate but then I lost that info.  Can anyone help?

    For the "Arangements" option to appear, the external display must be turned on with the correct input selected and connected to the computer.  Then close system prefs, reopen, go to "Display" and "Arrangement" will be along the top. 

  • Macbook air A1237 short circuiting

    I have just bought a macbook air A1237 the 13 inch screen - it was second hand and had a few problems.
    First problem was once turned on it was show the restart screen and that would be a constant loop, managed to fix that problem so it starts and works properly
    Second Problem - No battery, it wont hold charge - obvious fix replace the battery - need to do,
    Third Problem - No sound, the tricky one.
    The laptop had already been taken to a computer repair shop before i purchased the item - the shop is obvoiusly not competent enough to work on computers due to the fact they could not repair the restart problem (which took a non-computer techie less then 30 mins). and half of the screws from the device are missing - one on the case and all except one on the battery.
    I searched around on the net for a fix for the audio and found a tutorial that said remove the sound ribbon and place it above the battery, so i did this and it worked, turned the machine off and screwed the case back together and no sound... removed the case and i had sound ?? screwed the case back on whilst turned on i had sound for 2-4 hours before it went off... Still only works when the device has no bottom on,
    On anther note when i had the device with no bottom on i leaned over the machine and got a shock on my chin, didnt think anything of this due to the case being open, so screwed it all back together and thought f**k it, its a machine with no sound.
    After talking to a friend who loves his apple products he mentioned that the device could be short circuiting, so i checked the electric shock on my chin again and i got one from the device and every now when using it i get one on my arm or hand??
    So my question is - What could be causing the short and why is the device working properly apart from sound when short circuiting ??  
    Also i have downloaded OS lion - the machine is currently on OS X 10.6.8 and it will not let m upgrade? it starts the upgrade then just crashes ? any ideas?
    Ps. Sorry for my spelling.

    With the keyboard, if working correctly and marked as such, the "3" should also
    have the "#" as an option using the Shift key. There are additional hidden keys
    that these same buttons can provide, conditionally, with use of the "fn" function
    key; this acts like a super-shift key in certain instances. Some keys on a main
    external keyboard are condensed on a portable keyboard, & appear with 'fn'.
    To tell what the keyboard can provide in various alternatives, you could find
    and activate the Keyboard Viewer from within the System Preferences>
    International> Input Menu. With 'visible in menu bar' activated, one can
    more readily access it and the ability to tell what keys and shift, opt, etc
    combinations, or the fn key, can make appear in documents or elsewhere.
    The Keyboard Viewer opens into a small window on the desktop, so keys
    that are pressed are highlighted on a tiny screen in there. You can also click
    on the tiny keys in there to make them work in a document.
    Notice the choices in the Input Menu section, as you can set it so Character
    Palette and Keyboard Viewer both appear under the Flag icon in main Menu
    bar in the Finder or main desktop. Saves having to open Sys Prefs to see it.
    Some of the user interface points of reference change over time or between
    versions of OS X. So do some names of things, esp with Mt Lion/Mav. In a
    way it's good all older Intel-Macs can't run Mavericks 10.9.2. Less trouble.
    Other part sources?
    http://www.macrepairs.co.uk/parts/
    http://www.applemacparts.co.uk/store/macbook-air-c-8130.html
    Anyway, hopefully some of this helps a bit.
    Good luck & happy computing!

  • My printer makes a short-circuit on my telefphoneline when I plug it in so my fax can't function

    My printer makes a short-circuit on my telephone line when I plug it in so my fax can't function
    When I print (both not wireless and wireless) I can print maybe one or more pages and the the print stops half way in a pageprint for 30 sec to  1 or 2 minutes - and then continues the printing
    I bought the printer on jan. 11, 2011
    Do I miss to install a driver or.... is there a problem with the printer?

    You need to put the iPod into disk mode before it will show up on your desktop; if it is in disk mode and won't show up, open the Finder's preferences and check what's set to show up on the desktop.
    (10434)

  • Can i use Boolean Expressions in Mail Rules?

    Can i use Boolean Expressions in Mail Rules?
    I need to create a rule to check whether a message contains BOTH a first and last name of EITHER of two people.
    For example, the rule im looking to create goes something like this:
    If ANY of the following conditions are met:
    message content - contains - john & doe
    message content - contains - jane & doe
    ive tried and cant seem to get it to work...
    Message was edited by: mysterioso

    AFAIK Mail rules do not support boolean expressions.
    to do what you want you'd have to create two rules
    rule 1
    if ALL of the following conditions are met
    message content - contains - john
    message content - contains - jdoe
    and similarly for rule 2.

  • Search problems : Boolean expressions and spam folder

    I get about 1000 spam per day that I have to check.
    Some of them contains certain keyword that the real emails would never have.
    I would like to setup a smart folder or similar that found all emails in the spam folder that contains any of those keywords. I read some blogs etc. that said that spotlight boolean expressions could be used but they do not seem to work.
    e.g. "pill OR berry" yields no results at all but when each of the keywords are used on their own they produce 80 or so results each.
    Another problem I have is that I can do a manual search in the spam folder by typing in the search field and it yields results. But if I save that as a smart folder it yields no results at all. It seems that the rules do not work on the spam folder.
    I then tried to do all this from spotlight in the finder. I found the folder where the spam mailbox emails are stored (called "messages"). I managed to construct a nice search query and save it as a search. But if I delete one of the emails from the finder it still remains in Mail and the next time I start Mail it will be regenerated from somewhere.
    Anyone have any insights to provide here?

    I had actually missed that preference. Unfortunately it did not help.
    Even if I make a new smart mailbox with just one rule (the email must be in the spam folder) it doesnt work. It doesn't matter if I change between any/all either.
    I started experimenting with adding a rule saying that the email must not be in any of the other mailboxes but spam. That seemed to work for a bit but as I added more rules, excluding more mailboxes, it eventually broke. I will investigate it a bit more but currently don't have high hopes...

  • How to convert a boolean expression into a number in SQL (not PL/SQL)

    I have a boolean expression
    FIELD IN (SELECT FIELD FROM TABLE)
    which I would like to convert into a number, preferably into 0 for true and into 1 for false. The reason being that I want to sum the values in a HAVING clause.
    I have tried with DECODE, SIGN, TO_NUMBER, but all fail with an error message to the order of wrong type of argument.
    Does anyone have an idea?
    /poul-jorgen

    Hi, you can do it with case if you have Oracle 9i
    Regards
    Laurent
    select case when dummy in ('X') then 1 else 0 end from dual;

  • Dynamic execution of boolean expression

    Hi folks,
    I want to execute a boolean expression dynamically, can you pls help me how to do it.
    For example,
    String str = " ( X & ( Y | Z ) ) " ;
    They value of X , Y or Z will be either true or false.
    After replacing their value, I will get string as follow
    String result = "( true & (false | true ) ".
    Now I want to execute the String as boolean expression in order to get
    a result as a true or false.
    So, i need a solution to implement this. The expression may be simple or compound . It is so urgent waiting for your reply.
    Appreciated if you provide sample code.
    Thx !
    With regards,
    Rahul

    Java is a compiled language (well, strictly, a semi-compiled language.) This means that stuff like parsing expressions only happens at compile time. Variable names don't exist at run time, neither does the code which analyses expressions.
    If you really need to do this kind of thing, therefore, all the code for parsing these expressions has to be a part of your program, and stuff like values for variable names will have to be set explicitly by your program, not in regular variables but in variable list for the "scripting engine" you invoke.
    You can either write your own expression analyser (not a trivial task if you haven't done it before) or you can search arround the web for one someone else has written and find out if it covers your requirements. BeenShell has been suggested. Find it on the web and study it's documentation.
    Incidentally when the new release of Java comes out it will include serveral such "Scripting engines" for languages like JavaScript or Jython, and such things will be less hastle.

Maybe you are looking for