Reverse a list

Dave Cragg dave.cragg at lacscentre.co.uk
Sun Feb 15 07:56:04 EST 2015


Peter,

I don’t follow. If I change the repeat portion of your code to use repeat n times as below, the speed doesn’t change. And the speed scales linearly in both cases if the size of the data set is increased.

put the keys of pList into indexList
put the number of lines of indexList into i
put i into numTimes
  repeat numTimes times
     -- tLine is never used, but "repeat for each" is faster than "repeat <n> times"
     --    and this iterates the correct number of times
     put pList[i] & pDelim after outList
     subtract 1 from i
  end repeat

The advantage of "repeat for each" is when iterating over chunks in a string. (repeat for each line/item/word) In this case, we’re iterating over array elements, and so there is no advantage. If you look back at my earlier version which iterated through array elements from last to first, you’ll see it is basically doing the same as your reverseSort, and the times are also the same.

Cheers
Dave


> On 15 Feb 2015, at 04:31, Peter M. Brigham <pmbrig at gmail.com> wrote:
> 
> Harking back to the original discussion on reversing a list -- still the subject of this thread, here's the original example as I saved it in my library.
> 
> function reverseSort pList, pDelim
>   -- reverse sorts an arbitrary list
>   --    ie, item/line -1 -> item/line 1, item/line -2 -> item/line 2, etc.
>   -- pDelim defaults to cr
>   -- from an exchange on the use-LC list
>   --    this was the fastest pure LC method of several proposed
>   if pDelim = empty then put cr into pDelim
>   split pList by pDelim
>   put the keys of pList into indexList
>   put the number of lines of indexList into i
>   repeat for each line tLine in indexList
>      -- tLine is never used, but "repeat for each" is faster than "repeat <n> times"
>      --    and this iterates the correct number of times
>      put pList[i] & pDelim after outList
>      subtract 1 from i
>   end repeat
>   delete char -1 of outList
>   return outList
> end reverseSort
> 
> Note that the repeat is a "repeat for each line tLine…" even though the value of tLine is never actually used within the repeat loop. It's incredibly fast to do it that way, and it's an easy way to repeat something a foreseeable number of times. Using a "repeat n times" is glacial by comparison. I do agree that the dictionary should not just say the "repeat for each" form is much faster, it should say the "repeat for each" form is MUCH, MUCH faster.
> 
> -- Peter
> 
> Peter M. Brigham
> pmbrig at gmail.com
> http://home.comcast.net/~pmbrig




More information about the use-livecode mailing list