Alex Rivera | Logout

How do I take a slice of a list (A sublist) in scheme?

Asked 2008-09-20T13:36:52.200
17

Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?

EDIT:

Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.

Edit
Report

1 Answer

1

Try something like this:

    (define (slice l offset length)
      (if (null? l)
        l
        (if (> offset 0)
            (slice (cdr l) (- offset 1) length)
            (if (> length 0)
                (cons (car l) (slice (cdr l) 0 (- length 1)))
                '()))))
answered 2008-09-20T14:17:39.730

Your Answer