• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Position of an element in a list
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Position of an element in a list


  • Subject: Re: Position of an element in a list
  • From: jif <email@hidden>
  • Date: Mon, 31 Jul 2017 22:00:49 +0100

The possible index of an element in a list is an example of a class of
functions which really return a pair or tuple of values rather than a single
value.

You could think of the primary value as boolean (found | not found) possibly
paired (only if found is true) with an index integer.

A number of languages have particular syntax or conventions for handling these
dual values:

https://en.wikipedia.org/wiki/Option_type
<https://en.wikipedia.org/wiki/Option_type>

Applescript offers nothing specific, but a record with two key:value pairs
serves well.

We might avoid error handling in a simple iterative version of your function
(generalising to any data type which can be tested for equality with the
Applescript "=" operator) by writing something like this:


on elemIndex(x, xs)
        set lng to length of xs
        repeat with i from 1 to lng
                if x = (item i of xs) then return {just:i, nothing:false}
        end repeat
        return {nothing:true}
end elemIndex


on run
        set haystack to words of "alpha beta gamma delta epsilon zeta eta theta
iota kappa lambda mu"
        set needle to "kappa"

        set maybeIndex to elemIndex(needle, haystack)

        if nothing of maybeIndex then
                "Not found"
        else
                just of maybeIndex
        end if
end run

 _______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users

This email sent to email@hidden

  • Prev by Date: Position of an element in a list
  • Next by Date: Re: Position of an element in a list
  • Previous by thread: Re: set x to "0" = (do shell script "...") ???
  • Index(es):
    • Date
    • Thread