Group List by Number
| Function Syntax | (LM:GroupByNum <l> <n>) |
| Current Version | 1.0 |
| Arguments | ||
|---|---|---|
| Symbol | Type | Description |
| l | List | List to process |
| n | Integer | Number of elements by which to group the list (n > 0) |
| Returns | ||
| Type | Description | |
| List | A list of lists, each of length 'n', grouping elements of the original list | |
Program Description
This subfunction will group elements of a supplied list into lists of a specified length.
The function will return a list of lists, in which each list within the returned list is of the length specified by the function arguments.
Should the supplied list not divide evenly into lists of the specified length, nil values will occupy the remainder list elements.
Recursive Version
Select all
;;-----------------=={ Group by Number }==--------------------;; ;; ;; ;; Groups a list into a list of lists, each of length 'n' ;; ;;------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2010 - www.lee-mac.com ;; ;;------------------------------------------------------------;; ;; Arguments: ;; ;; l - List to process ;; ;; n - Number of elements by which to group the list ;; ;;------------------------------------------------------------;; ;; Returns: List of lists, each of length 'n' ;; ;;------------------------------------------------------------;; (defun LM:GroupByNum ( l n / r ) (if l (cons (reverse (repeat n (setq r (cons (car l) r) l (cdr l)) r)) (LM:GroupByNum l n) ) ) )
Iterative Version
Select all
;;-----------------=={ Group by Number }==--------------------;; ;; ;; ;; Groups a list into a list of lists, each of length 'n' ;; ;;------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2010 - www.lee-mac.com ;; ;;------------------------------------------------------------;; ;; Arguments: ;; ;; l - List to process ;; ;; n - Number of elements by which to group the list ;; ;;------------------------------------------------------------;; ;; Returns: List of lists, each of length 'n' ;; ;;------------------------------------------------------------;; (defun LM:GroupByNum ( l n / a b ) (while l (repeat n (setq a (cons (car l) a) l (cdr l) ) ) (setq b (cons (reverse a) b) a nil ) ) (reverse b) )
Example Function Calls
_$ (LM:GroupByNum '("A" "B" "C" "D" "E" "F") 2) (("A" "B") ("C" "D") ("E" "F")) _$ (LM:GroupByNum '(0 1 2 3 4 5) 3) ((0 1 2) (3 4 5))
