Search code examples
applescript

Is there a range function to create a list of numbers?


I'm looking to make a consecutive list of numbers in Applescript. One could create such a list using a repeat loop, but that seems messy. Is there anything that works like this?

range from 1 to 10
-> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Solution

  • Yes, answering the last question first, there is (using four more lines) a list-of-lists repeat loop:

    set nlist to {}
    repeat with n from 0 to 9
        set nlist2 to {n + 1}
        set nlist to nlist & nlist2
    end repeat
    nlist
    --> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    

    Basically, if you repeatedly merge lists, you create a list of lists, whereas...

    set nlist to {}
    repeat with n from 0 to 9
        set nlist to {n + 1}
    end repeat
    nlist
    --> {10}
    

    ...would just result in the last number of the loop. (Surely, there must be other ways, too.)

    The closest one-line equivalent of ranges is probably "items 1 through 10" -but only for an existing list; example:

    set rangeB to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
    set nlist to items 1 thru 10 of rangeB
    nlist
    -->{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

    Regarding the title question, if it's a function you need, in Applescript they are called handlers, there is no preset range function, but you may create a customized range function for your task like this:

    on range(a, b)
    set nlist to {}
    repeat with n from a - 1 to b - 1
    set nlist2 to {n + 1}
    set nlist to nlist & nlist2
    end repeat
    end range
    --
    range(5, 20)
    -->{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

    • And I think the real question behind the question (which I just recently had myself) was: "I'm coming from the world of spreadsheets, where are the ranges, where are the functions in AppleScript?" And the answer to that is: Ranges are now really lists, or items of a list, functions are handlers which you need write once, it's a bit extra work at first, but the upside is how easy then -and helpful- it can be to add customized functions, a whole new range (correction: list) of possibilities. And the AppleScript repeat loops are what the copy/paste down was in spreadsheets, essentially saying, in comparison: here is a function, I'd like to apply this to list A and it gets me list B with results, and repeat it again, from here to there. (Or non-stop.) Yes, copy/paste-down seems easier at first, and repeat with its "repeat with i" looks a bit esoteric at first, I agree, but on further consideration it is actually pretty straightforward, and there is really no way around it in so many coding situations. It's a core engine! "Eat, sleep, rave, repeat!" ;D And the repeat loops can be upgraded, again: offering more practical possibilities than the spreadsheet way of copy/paste-down.