[racket] Building an indexing function for lists-of-lists

From: Rian Shams (rian.shams at gmail.com)
Date: Mon Jan 13 18:06:11 EST 2014

I am trying to build the following indexing function:

;list-of-lists beginning-index-number -> list-of-lists
;The purpose of this function is to convert one list into another list of
incremental numbers, while at the same time, maintaining the structure of
the original list. To basically number each point/node in a given list, and
return the new numbered list in the same form as the original.

Here is what I have so far which works in some instances, but not in others:

(define (index-s-exp s-exp index)
  (cond [(empty? s-exp) empty]
           [(atom? (first s-exp))
            (cons index
                     (index-s-exp (rest s-exp) (add1 index)))]
           [else
            (cons (index-s-exp (first s-exp) index)
                     (index-s-exp (rest s-exp) (add1 index)))]))


>(index-s-exp '(+ .3 (- .1 x))  1)
'(1 2 (3 4 5))
this works (I think because the redex is always in tail-position and
therefore matches Racket's evaluation scheme)

>(index-s-exp '(+ (- .1 .2) .3)  1)
'(1 (2 3 4) 3)
This doesn't work, desired result is '(1 (2 3 4) 5)

I was wondering how I might be able to modify this function so that it
works in both cases, as well as if there are any built-in functions that I
can take advantage of to make this function cleaner?

Thanks,
-- 
Rian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140113/79b8df1d/attachment.html>

Posted on the users mailing list.