Arc Forumnew | comments | leaders | submitlogin
How would you do this? Splitting a list into a list of lists of equal size
1 point by hasenj 5134 days ago | 4 comments
In other words, (pair list) but the pair size doesn't need to be 2

Looking at pair's implementation doesn't help much,

  (def pair (xs (o f list))
    (if (no xs)
       nil
      (no (cdr xs))
       (list (list (car xs)))
      (cons (f (car xs) (cadr xs))
            (pair (cddr xs) f))))
Seems rather cryptic and hard to play with :/

This is how I'd do it in python:

    def split_to_groups(list, size):
        groups = []
        for s in range(0, len(list), size):
            groups.append(list[s:s+size])
        return groups
Test:

  >>> split_to_groups(range(20), 3)
  [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19]]


3 points by conanite 5134 days ago | link

  arc> (tuples (range 0 19) 3)
  ((0 1 2) (3 4 5) (6 7 8) (9 10 11) (12 13 14) (15 16 17) (18 19))
tuples is defined in arc.arc:

  (def tuples (xs (o n 2))
    (if (no xs)
        nil
        (cons (firstn n xs)
              (tuples (nthcdr n xs) n))))

-----

1 point by hasenj 5134 days ago | link

Thanks!

Interestingly, it's smaller than 'pair' even though it does more.

-----

3 points by akkartik 5133 days ago | link

I first encountered this idea in a theorem-proving class - that if you have a hard time proving a theorem, often a really good approach is to find a more general 'lemma' to try to prove. Stronger theorems are often easier because they let you assume more in the induction step. Recursion has a similar 1-1 correspondence with inductive proofs.

http://www.cs.utexas.edu/users/moore/classes/cs389r/index.ht...

-----

1 point by hasenj 5133 days ago | link

Actually I just realized, 'tuple' uses 'firstn' and 'nthcdr', where as 'pair' sort of inlines these concept and has to deal with nils.

-----