[racket] circular lists are not lists or sequences

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Mon Dec 10 11:00:26 EST 2012

2012/12/10 David Van Horn <dvanhorn at ccs.neu.edu>:
> On 12/10/12 10:14 AM, Matthew Flatt wrote:
>>
>> We did change `in-list' to add a `list?' guard, so the behavior is as
>> intended. Maybe we need a new `in-' sequence constructor that works as
>> long as pairs appear for as far as you demand sequence elements?
>
>
> Yes, an `in-pairs' seems right to me.  I can submit a pull request if that
> design is OK.

I'd like to lobby that in-pairs is the following,
wherein the clause [p (in-pairs '(1 2 3))] lets binds p
to the pairs of the list.

(define (in-pairs xs)
  (make-do-sequence
   (λ ()
     (define (pos->element p) p)
     (define (next-position p) (cdr p))
     (define initial-position xs)
     (define (continue-with-pos? p) (pair? p))
     (values pos->element
             next-position
             initial-position
             continue-with-pos?
             #f #f))))

Examples:

> (for ([p (in-pairs '(1 2 3 4))])
    (displayln p))
(1 2 3 4)
(2 3 4)
(3 4)
(4)


(define (deltas xs)
  (for/list ([p (in-pairs xs)]
             #:when (pair? (cdr p)))
    (- (cadr p) (car p))))

> (deltas '(1 3 7 13))
'(2 4 6)



/Jens Axel


Posted on the users mailing list.