I wanted to write a code in Scheme that writes the square odd elements in list.For example (list 1 2 3 4 5) for this list it should write 225.For this purpose i write this code:
(define (square x)(* x x))
(define (product-of-square-of-odd-elements sequence)
(cond[(odd? (car sequence)) '() (product-of-square-of-odd-elements (cdr sequence))]
[else ((square (car sequence)) (product-of-square-of-odd-elements (cdr sequence)))]))
For run i write this (product-of-square-of-odd-elements (list 1 2 3 4 5))
and i get error like this:
car: contract violation
expected: pair?
given: '()
What should i do to make this code to run properly? Thank you for your answers.
First of all, you need to do proper formatting:
Now there are multiple issues with your code:
You are trying to work recursively on a sequence, but you are missing a termination case: What happens when you pass
'()- the empty sequence? This is the source of your error: You cannot access the first element of an empty sequence.You need to build up your result somehow: Currently you're sending a
'()into nirvana in the first branch of yourcondand put a value into function call position in the second.So let's start from scratch:
You process a sequence recursively, so you need to handle two cases:
Let's take the recursive case first: You need to compute the square and multiply it with the rest of the squares (that you'll compute next).
In the termination case you have no value to square. So you just use the unit value of multiplication:
1This is not a good solution, as you can transform it into a tail recursive form and use higher order functions to abstract the recursion altogether. But I think that's enough for a start.