First I wonder if these exists already somewhere, I was not able to find 
exactly these in itertools module or somewhere else. (In case you find then 
strange -- such iterators are needed for example when we have a set of points 
in 2D and want to examine if the points build a convex polygon, so we have to 
examine 3 consecutive points each, continuing from beginning for the last two.) 
Better names or other suggestions welcome.
    
    
     xpairs*[T](a: openarray[T]): array[2, T] {.inline.} =
      var i, j: int
      while i < len(a):
        inc(j)
        if j == a.len:
          j = 0
        yield [a[i], a[(j)]]
        inc(i)
    
    for xp in xpairs([1, 2, 3, 4, 5]):
      echo xp
    echo ""
    
    iterator xclusters*[T](a: openarray[T]; s: static[int]): array[s, T] 
{.inline.} =
      var result: array[s, T] # iterators have no default result variable
      var i = 0
      while i < len(a):
        for j, x in mpairs(result):
          x = a[(i + j) mod len(a)]
        yield result
        inc(i)
    
    for xp in xclusters([1, 2, 3, 4, 5], 2):
      # echo xp
      var u, v: int
      (u, v) = xp # tuple unpacking works for arrays too!
      echo u, ", ", v
    echo ""
    
    for xp in xclusters([1, 2, 3, 4, 5], 3):
      echo xp
    
    Run

Reply via email to