Other answers give good ways to do this, however, what you are describing is basically an O (n ^ 2) operation, assuming you are really implementing all the lazy sequences, etc. It probably would not be a good idea if n> = 1,000,000
Perhaps you should consider expanding the scope of the code that you plan to see if you can find a more efficient algorithm in general.
For example, you may find that it is best to convert the entire list to a vector and write your algorithm in terms of indexed access into a vector.
source share