I am trying to make a function that takes 2 numbers and will create a list using the first number as a starting number and the second number as the ending value while filling in the values between the starting and ending numbers.
For example:
User passes in 3 and 7:
the output should be (3 4 5 6)
I was trying to do this and use recursion but I am struggling:
(define (createlist start end)
(if(= start end)
'())
(cons start '())
(createlist (+ 1 start) end))
There’s a repeating pattern found in the solution to this sort of problems where you have to build a list along the way using recursion. Let me illustrate the general steps, I’ll let you fill-in the blanks:
The idea of the algorithm is that at each step we add the current
startvalue to the list that is being built withcons, and incrementstartuntil it reachesend, at this point the recursion ends.You should take a look at either The Little Schemer or How to Design Programs, both books will teach you how to structure the solution for this kind of recursive problems over lists.
UPDATE:
Now that you’ve posted the code you’ve written so far, I can show you the right answer. Please be very careful with parenthesis [ the closing parenthesis of an
ifgoes after theelsepart ] and white spaces [if(is not the same asif (], they matter a lot in Scheme. Also indent correctly your code, it’ll help you find a lot of bugs:Now you can see how the
<???>get correctly filled.