[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: Grouping list elements

William James

9/6/2015 4:57:00 PM

Drew Crampsie wrote:

> (defun split-list (n list)
> (loop for cons on list
> by #'(lambda (x) (nthcdr n x))


The abysmal ignorance of the typical worshipper of CL (COBOL-Like) and
LOOP. Why didn't he simply say:

by (lambda (x) (nthcdr n x))


> if (< 0 n)
> collect (loop for atom in cons
> repeat n
> collect atom)
> else return nil))

Why did he put the check for n > 0 inside of the Loop?
This is shorter and clearer:

(defun split-list (n list)
(and (< 0 n)
(loop for cons on list
by (lambda (x) (nthcdr n x))
collect (loop for atom in cons
repeat n
collect atom))))

>
> CL-USER> (split-list 0 (list 1 2 3 4 5 6 7 8))

Why does he want to be so long-winded?
Why not:

(split-list 0 '(1 2 3 4 5 6 7 8))

Why doesn't he use a sensible language in which he can say:

(split-list 0 (iota 8))


> NIL
> CL-USER> (split-list 1 (list 1 2 3 4 5 6 7 8))
> ((1) (2) (3) (4) (5) (6) (7) (8))
> CL-USER> (split-list 3 (list 1 2 3 4 5 6 7 8))
> ((1 2 3) (4 5 6) (7 8))
> CL-USER> (split-list 40000 (list 1 2 3 4 5 6 7 8))
> ((1 2 3 4 5 6 7 8))


Gauche Scheme:

(use srfi-1 :only (unfold))

(define (split-list n items)
(if (< n 1)
'()
(unfold null? (cut take* <> n) (cut drop* <> n) items)))


A version that's easier for a tyro to understand:

(define (split-list n items)
(if (< n 1)
'()
(unfold ;; Generate a list from a seed.
null? ;; Stop when seed is empty.
(lambda (x) (take* x n)) ;; Next item for result.
(lambda (x) (drop* x n)) ;; Generate next seed.
items ;; The seed.
)))


gosh> (split-list 0 (iota 8))
()
gosh> (split-list 1 (iota 8))
((0) (1) (2) (3) (4) (5) (6) (7))
gosh> (split-list 3 (iota 8))
((0 1 2) (3 4 5) (6 7))
gosh> (split-list 333 (iota 8))
((0 1 2 3 4 5 6 7))


Gauche already has "slices":

gosh> (slices (iota 8) 3)
((0 1 2) (3 4 5) (6 7))
gosh> (slices (iota 8) 3 #t 0)
((0 1 2) (3 4 5) (6 7 0))

--
The report card by the American Society of Civil Engineers showed the national
infrastructure a single grade above failure, a step from declining to the point
where everyday things simply stop working the way people expect them to. ---
washingtonpost.com/local/trafficandcommuting/us-infrastructure-gets-d-in-annual-report/2013/03/19/c48cb010-900b-11e2-9cfd-36d6c9b5d7ad_story.html