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)