In: Computer Science
In racket
Assume that the elements of a list are indexed starting with 1. Write a function alts that takes a list of integers xs and returns a pair of lists, the first of which has all the odd-indexed elements (in the same relative order as in xs) and the second of which has all the even-indexed elements (in the same relative order as in xs).
Output should be
(alts (list 7 5 4 6 9 2 8 3)) '((7 4 9 8)5 6 2 3)
(alts (list 5 4 6 9 2 8 3)) '((5 6 2 3) 4 9 8)
Any help would be appreciated, we're not allowed to use cond
Code:
(define (alts List)
(if (null? List) ;;if list is empty returns NULL list
'()
(append (list (first List)) (second List)))) ;;else append odd
indexed elements list wit elements of even indexed
;;SUB_Function returns odd indexed List
(define (first List)
(if (null? List) '() ;;if list is empty returns NULL list
(if (null? (cdr List)) List ;;if list has only one element return
that element
(cons (car List) ;;else create list with first element and
(first (cdr (cdr List))))))) ;;call function recursively with list
starting with next odd index
;;SUB_Function returns Even indexed elements List
(define (second List)
(if (null? List) '() ;;if list is empty returns NULL list
(if (null? (cdr List)) '() ;;if list has no second element return
empty list
(cons (car (cdr List)) ;;else create list with second element
and
(second (cdr (cdr List))))))) ;;call function recursively with list
starting with next even index
Snapshot of Code and Output: