Idiomatic lisp - loops
- From: oversby@xxxxxxxxxxxxxx
- Date: 16 Mar 2007 11:00:40 -0700
Hi,
I'm trying to write a loop that inserts a dotted key/value pair in
order into a list of ordered
key/value pairs.
So far I've got a recursive solution:
(defun kv-insert (list elt)
(if (null list) '()
(let* ((h (car list))
(k1 (car elt))
(k2 (car h)))
(cond ((string< k1 k2) (cons elt list))
((string= k1 k2) (cons elt (cdr list)))
(t (cons h (kv-insert (cdr list) elt)))))))
and an iterative solution:
(defun kv-insert (list elt)
(let ((k1 (car elt))
(acc '()))
(while (not (null list))
(let* ((h (car list))
(k2 (car h)))
(cond ((string< k1 k2)
(setq acc (append (reverse list)
(list elt)
acc))
(setq list '()))
((string= k1 k2)
(setq acc (append (reverse (cdr list))
(list elt)
acc))
(setq list '()))
(t (setq acc (cons h acc)))))
(setq list (cdr list)))
(reverse acc)))
neither of which I'm particularly happy with.
In scheme I would use letrec to avoid needing to pass the elt
parameter to each
loop iteration. Is there something similar in lisp or an alternative
idiomatic way
to write this loop?
(define (kv-insert l elt)
(letrec ((k1 (car elt))
(loop (lambda (l)
(if (null? l) '()
(let* ((h (car l))
(k2 (car h)))
(cond ((string< k1 k2) (cons elt l))
((string= k1 k2) (cons elt (cdr l)))
(else (cons h (loop (cdr l))))))))))
(loop l)))
Thanks,
Ian
.
- Follow-Ups:
- Re: Idiomatic lisp - loops
- From: Raffael Cavallaro
- Re: Idiomatic lisp - loops
- From: Rob St. Amant
- Re: Idiomatic lisp - loops
- From: Pillsy
- Re: Idiomatic lisp - loops
- Prev by Date: Re: Resolving Conflicts between (invoke-restart) and (in-package)?
- Next by Date: Re: learning Common Lisp ;; i came back Full-Circle
- Previous by thread: learning Common Lisp ;; i came back Full-Circle
- Next by thread: Re: Idiomatic lisp - loops
- Index(es):
Relevant Pages
|