1

I could not find a similar problem here, but I'm trying to write a program in scheme for a class so hints would be very well appreciated! I'm basically confused as to how to implement this but here is an example on how it's supposed to work. (index 5) is supposed to return the list (1 2 3 4 5). I have a couple of ideas, could they work?

  1. I make the argument a global variable which I increment each time I call the function recursively. the problem I've had with this so far is that using set! returns a list but the output would look something like this (#value #value....)

  2. program a simple recursive function that gives the list (5 4 3 2 1) and then reverse it, but would I be able to do that?

2 Answers 2

0

I'd go with solution 2 as it is by far the cleanest, least complicated option. You just need to figure out the recursion. Hint: the base case is reached at (index 0), which should return the empty list. Reversing afterward can be done by putting actual recursion in a helper function:

(define (index-r n)
  ...)

(define (index n)
  (reverse (index-r n)))

(Or use a named-let loop.)

1
  • thanks lars! wasn't aware that there was an inbuilt reverse function in scheme
    – steve
    Commented Sep 25, 2012 at 11:33
0

program a simple recursive function that gives the list (5 4 3 2 1) and then reverse it, but would i be able to do that?

Why not directly write a recursive function that gives the list (1 2 3 4 5) ?? In "pseudo code" so that I don't do it for you:

f(x) = cons x (f(x+1))
f(5) = (list 5)

and then, call f(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.