September 24, 2003

Fun AppleScript Tricks (or not)

Filed under: Reanimate — Ryan Wilcox @ 3:56 pm

Take a look at the following Applescript. What do you expect to happen in both cases?

Snippet #1

set ab to {"a", "b"}
set alpha to {"a", "b", "c", "d"}

if ab is in alpha then
log ("ab in alpha")
else
log ("ab not in alpha")
end if

Snippet #2

set ab to {"a", "c"}
set alpha to {"a", "b", "c", "d"}

if ab is in alpha then
log ("ab in alpha")
else
log ("ab not in alpha")
end if

Click below for the answer to the riddle

Guessed it?

Snippet #1 will return “ab in alpha”, while snippet #2 will return “ab not in alpha”.

With this construct we are not asking “are these two items in the list, good sir?”, we are asking “are these two items in the list together, sir?”

To put it politely, that was unexpected. At least to me.

I tried to do a “are any of the list items from this one list in this other list” in Python, and it won’t let me (runtime error). I have to compare each object from list A to see if it’s list B. In one way, this feels somewhat dumb – in another way, this avoids the whole situation together.

So, like Python, I’m writing a loop in Applescript to do the compare. But I wasted at least 15 minutes more time than I should have on figuring out that the whole thing doesn’t work.

You have been warned. I wish I would have been.

1 Comment

  1. I write this as follows…
    set allHit to true
    repeat with each in ab
    if each is not in alpha then
    set allHit to false
    exit repeat
    end
    end

    The puzzle basically breaks down to a boolean AND test so as soon as you find one item that fails, you can bail out.
    If you want to check for any of the items (a boolean OR) try this…
    set anyHit to false
    repeat with each in ab
    if each is in alpha then
    set anyHit to true
    exit repeat
    end
    end

    Comment by Matt Strange — September 24, 2003 @ 4:06 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.