scheme: return a lst that only contains the first

2019-08-04 08:33发布

问题:

Here is the question:

Write a function (first-n-elements lst n), which returns a list containing only the first n elements of lst. For example, (first-n-elements '(1 2 3 4 5 6) 3) should return '(1 2 3). Your function should handle the case where n is greater than the length of the list (in which case it would return the entire list), and where n is 0 (should return '()).

My answer is:

(define (first-n-elements lst n)
  (cond((null? lst) '())    
       ((= n 0) lst))   
       ((> n 0) (cons (+ (car lst) 1) (first-n-elements) (cdr lst) (- n 1))))

I know it's wrong, please help

回答1:

Part of the question says that if n is 0, it should return '(). But what does your function do when n is 0?

Also, think about the recursive case here (> n 0). You're currently returning the cons of four arguments:

  • (+ (car lst) 1)
  • (first-n-elements)
  • (cdr lst)
  • (- n 1)

But cons only takes two arguments. You have all the parts there, but they're not quite put together right. What do you want to be consing together?

Also: why are you adding 1 to (car lst)? That's not going to work if lst has something other than numbers in it.



回答2:

You've got a natural number and a list, and you need to do the recursion on both of them. See this chapter on recursion on two complex arguments. The short answer is that you've got to consider all combinations of the cases for the two arguments (the Cartesian product, essentially). Of course, you may find that some of the cases can be collapsed together, but when in doubt, start by considering them each separately.



标签: scheme