Question

I'm trying to print the first 2 numbers in a list coded in Scheme. I'm having a bit of trouble doing this. I get an error when I run the procedure. Any suggestions on how I can get this to work

(define (print-two-nums n nums)

( list-ref nums(+ (cdr nums) n))) ( print-two-nums 2'(5 5 4 4))

Was it helpful?

Solution

It looks like you were wavering between the ideas of "print two numbers" and "print n numbers." If you really want just the two first numbers of a list, you can write:

(define (print-two-nums nums)
  (print (list (car nums) (cadr nums))))

But for the more general first n numbers, you can use:

(define (print-n-nums n nums)
  (print (take nums n)))

OTHER TIPS

To print the first n numbers, you could use this simple procedure

 (define (print-n-nums L n) (cond
                   ((or (= 0 n) (null? L)) '())
                   (else (cons (car L) (print-n-nums (cdr L) (- n 1))))))



(print-n-nums (list 1 2 3) 2)
;Output: (1 2)

You could further abstract the cons operation and define print-n-nums as a higher order procedure to carry out the desired operation. For example, if we wanted to add the first n numbers of a list, we could define the following procedure. Here OPERATION is a function that we pass to the list-operator function. Thus, here we want to perform the + operation. In the case above, we want to perform the cons operation. The initial parameter is just how we want to handle the edge case.

(define (list-operator L n OPERATION initial) (cond
           ((or (= 0 n) (null? L)) initial)
           (else (OPERATION (car L) (list-operator (cdr L) (- n 1) OPERATION initial)))))

(list-operator (list 1 2 3) 2 + 0)
;Output: 3

Now, if you wanted the product of the first 2 numbers, you would just do

(list-operator (list 1 2 3) 2 * 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top