In: Computer Science
Hello. Please answer the following two-part question in Scheme. Not Python, not any form of C, but in the language Scheme. If you do not know Scheme, please do not answer the question. I've had to upload it multiple times now. Thank you.
3.1 Write a recursive function called split
that takes a list and returns a list containing two lists, each of
which has roughly half the items in the original list. The easiest
way to do this is to alternate items between the two lists, so that
(split '(1 2 3 4 5)) would return '((1 3 5) (2 4)). I recommend
using two base cases: one for an empty list and the other for a
list containing one item.
> (split '())
(() ())
> (split '(3))
((3) ())
> (split '(4 8))
((4) (8))
> (split '(8 6 7 5 3 0 9))
((8 7 3 9) (6 5 0))
3.2 Write a recursive function called merge that
takes two sorted lists of numbers and merges them together into one
sorted list containing all of the number in both lists including
duplicates.
> (merge '() '())
()
> (merge '() '(1 2 3))
(1 2 3)
> (merge '(1 2 3) '())
(1 2 3)
> (merge '(2 4 7) '(1 3 5))
(1 2 3 4 5 7)
SCHEME SPLIT
(define split
(lambda (L)
(if (null? L)
'()
(list (first L) (second L)))))
(define first
(lambda (L)
(cond ((null? L) '())
((null? (cdr L)) L)
(else (cons (car L)
(first (cdr (cdr L))))))))
(define second
(lambda (L)
(cond ((null? L) '())
((null? (cdr L)) '())
(else (cons (car (cdr L))
(second (cdr (cdr L))))))))
SCHEME Merge
(define (merge-sort 1 gt?)
(define (merge left right)
(cond
((null? left)
right)
((null? right)
left)
((gt? (car left) (car right))
(cons (car right)
(merge left (cdr right))))
(else
(cons (car left)
(merge (cdr left) right)))))
(define (take l n)
(if (zero? n)
(list)
(cons (car l)
(take (cdr l) (- n 1)))))
(let ((half (quotient (length l) 2)))
(if (zero? half)
l
(merge (merge-sort
(take l half) gt?)
(merge-sort (list-tail l half) gt? )))))