0
votes

I need a function that will do this:

Odd Length list Input '(1 2 3 4 5) = '(1 (2 (3) 4) 5)

Even length list Input '(1 2 3 4) = '(1 (2 () 3) 4)

It needs to use very minimal built in functions. I have spent hours trying to figure this out and I am completely out of ideas at this point.

Here is what I have:

(define (listInList L)
    (define length (listLength L))     
    (define L2 (listInListHelper length L '() '()))
    (define L3 (listInListHelper (- length 2) L L2 '()))
    L3
)

(define (listInListHelper N L NL)
(cond
    ((= N 0) '()
    ((= N 1) (cons (list (car L)) NL))
    (else (cons (cons (car L) (list (lastItem L))) NL)
    (remove 1 L)))     
)
)

(define (lastItem L)
(if (null? (cdr L))(car L)
    (lastItem (cdr L)))
)

(define (remove N L)
(cond ((eq? N 0) (cdr L))
    (else (cons (car L) (remove (- N 1)(cdr L))))))
1

1 Answers

1
votes

This would be one way to do it, you need to tell me if it's minimal enough:

(define (f lst)
  (define (helper lst rlst half)
    (cond
      ((= half 0 )  null)
      ((= half 1/2) (list (car lst)))
      (else         (list (car lst)
                          (helper (cdr lst) (cdr rlst) (sub1 half))
                          (car rlst)))))
  (helper lst (reverse lst) (/ (length lst) 2)))

testing:

> (f '(1 2 3 4 5))
'(1 (2 (3) 4) 5)
> (f '(1 2 3 4))
'(1 (2 () 3) 4)