1
votes

My question is really one of logic more than anything, the task is to truncate a list to a given length in racket. That is, given a list (A B C), and a given length of 2, I would want a new list of (A B). The constraint being that we have a restricted list of available functions, of which I will put below. I apologies if this question is simple but I'm having a tough time and just cannot work out the sequence necessary. If someone could even just point me in the right direction, that would be wonderful.

List of Functions:

  • cons, car, cdr, define, quote, if, cond, else
  • Basic forms of Arithmetic (+, -, *, /)
  • very basic tests (basic numeric comparisons, null?, list?, eq?)

I have already created a function that returns the length of a list, I also understand this will require some form of recursion.

1
Let me thank you for pointing out in the title that you are not working in the full Racket language: I find questions that impose arbitrary constraints without being up front about it infuriating, and this was a breath of fresh air.Alexis King

1 Answers

1
votes

I won't spoil the fun of reaching the answer by your own means (after all you asked for pointers), so I'll give you some hints. This problem is solved by using the standard template for recursively traversing a list (we process the first element and then call the recursion with the rest of the elements) and building an output list (using cons), take note of it as you'll be using it repeatedly. Just fill-in the blanks:

(define (truncate lst n)
  (cond ((null? lst) ; if the list is empty then n is invalid
         <???>)      ; and you should signal an error
        ((= n <???>) ; if n is zero we're done
         <???>)      ; return an empty list
        (else        ; otherwise build the output list
         (cons <???> ; cons the first element in the list and call the recursion
               (truncate <???> <???>))))) ; move to the rest of the list, decrement n

The first condition is optional, if you can assume that the number of elements to truncate is correct, simply remove it. It should work as expected:

(truncate '(A B C) 2)
=> '(A B)