Scheme has a built in procedure for splitting lists, but usually you can’t use unlearned methods in labs or in homework yet. So this is a partial solution for splitting a list at a particular index.
; split's a list ; lst - a list to be split ; at - a numeric index at which to split the list (define (split lst at) ; splits the list ; n - new list ; l - an old ; i - a counter (define (iter n l i) (if (or (null? l) (= i at)) (cons (reverse n) l) (iter (cons (car l) n) (cdr l) (+ i 1)) ) ) (iter () lst 0) )
Here’s the algorithmic process.
- Add the first element from the old list to the new list
- Remove the first element from the old list
- Repeat with the new and old list
- Until either the list is null or the counter as reached the designated index
There are two arguments for this procedure. The first is the list itself to be split. The second is a simple integer. To get the split parts of the list, you’ll have to
cdr the result. For example,
(car (split a-list 3)) will return the first portion of the list while a
(cdr (split a-list 3)) will return the latter half of the list.
Here’s some sample output.
original: (0 1 2 3 4 5 6) split at index: 3 first: (0 1 2) tail: (3 4 5 6) original: (hello world how are you doing today ?) split at index 4 first: (hello world how are) tail: (you doing today ?)
Splitting lists in Scheme is really handy.