0

I can get the odd elements of a list using the following code:

(define (odds lis)
(cond
    ((null? lis) '())
    ((not (list? lis)) (quote (Usage: odds(list))))
    ((null? (car lis)) '())
    ((= (length lis) 1) (car lis))
    (else (cons (car lis) (odds (cddr lis))))))

but when input list of odd length For example: (odds '(a b c d e)) It will return (a c . e)

How can i get rid of this obnoxious period?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user1822789
  • 45
  • 2
  • 6

1 Answers1

0

Try this, it's a change in only one line:

(define (odds lis)
  (cond
    ((null? lis) '())
    ((not (list? lis)) (quote (Usage: odds(list))))
    ((null? (car lis)) '())
    ((= (length lis) 1) lis) ; change here
    (else (cons (car lis) (odds (cddr lis))))))

In the highlighted line, you were returning a single element instead of a proper list (a null-terminated list), that's what was causing the problem.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Even easier: instead of `(list (car lis))`, just use `lis` directly. It is, at that point, a singleton list already. – C. K. Young Nov 15 '12 at 00:59