0
votes

This is a hw assignment that requires me to write a scheme function that takes a function(with two params) and a list as parameters, then returns a list where each consecutive pair of the elements of the list is replaced by the value of the function applied to these two elements.

For example - If the list has an odd number of elements, the last element is ignored. For example, (apply-to-pairs (lambda (x y) (+ x y)) '(3 9 5 8 2 4 7)) should return (12 13 6).

so far what I have got is:

(define (fn-name fn l)
  (if (null? (cdr l))null
      (cons 
        (fn((car l)(car (cdr l)))
         (fn-name fn (cdr l))))))

However, im getting this error in Racket(DrRacket):

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 3
  arguments...:
   9

... and it highlights fn((car lst)(car (cdr lst))). I'm trying to find out how to handle the function parameter. Thanks for the help!

1
A Google search for "application: not a procedure" site:stackoverflow.com turns up lots of results that explain this for you: you've got extra parens. (fn ((car l) (car (cdr l)))) should be (fn (car l) (car (cdr l))). Generally, when you encounter an error, you'll do well to search for the exact error message.Joshua Taylor

1 Answers

2
votes

As you already did you just apply fn like you would with any primitives like +. However you have extra parenthesis around (car lst) and (car (cdr lst)) which means you expect first element to also be a procedure you call with the second element as it's only argument and then fn only get one argument (the result of that if 3, 5 or 2 happens to be procedures) Perhaps you instead wanted (fn (car lst) (cadr lst)) (I'm using shothand for car+cdr)

Your base case should check both l and (cdr l) for null since if either one is you are fnished. (Try calling it with (fn-name + '(5))). You can use special form or to do that like (or test1 test2).

Also notice that null is not usually a bound symbol in Scheme. You either need to define it (define null '()) or use '().

EDIT ABout too many results..

Notice that when you have applied the first round withe the first two elements of the list you recurse with a new l starting at the list except the very first element.. That means you then will process 9 and 5 in the next iteration instead of 5 and 8. To fix that you need to use cddr (cdr+cdr) instead of just cdr.