I'm trying to create a function that will return the even numbered elements in a list.
For example:
(evens '(a b c d))
should return
(b d)
The code below seems to work for lists that have and odd numbers of elements, but if I give it a list with an even number of elements, it is incorrect.
For example:
(evens '(a b c d e))
will return
(b d)
But:
(evens '(a b c d))
will return
(a c)
Any thoughts?
Changed my code to:
(DEFINE (evens lis)
(cond
((null? lis) '())
(else (cons (cadr lis) (evens (cdr lis))))
))
Gets a error saying that the object passed to safe-car is not a pair?
Your code has few missing checks and a bit of incorrect logic.
I'm going to answer your question with commented examples, in the hope that you actually learn something instead of just being given code that works. Actually, looking at several pieces of code may be more enlightening, assuming that you're new to scheme.
Your original definition looked like this:
Afterwards, you've edited your question to update it to something like this:
A solution is to check if the list has at least a second element:
Exercise: Use
if
andor
to simplify this solution to only have 2 branches.This same question has been asked time and again over the last couple of days. I'll give a direct answer this time, to set it straight:
And here's how to do some error checking first:
The problem is that if your list has an even number of elements, the
modulo
branch is matched and you startcons
ing with thecar
of the list ... hence in your example, you get thea
, and so on.More importantly, though, you don't need to use
length
for this function ... and you shouldn't: sincelength
takes linear time in the length of the list,evens
now takes quadratic time.Suggestion: your program should 'remember' whether it's in an 'odd' or 'even' location at each recursive step ... how could you do this (there are several ways)?