Carter Wilson
Carter Wilson

Reputation: 69

Scheme function as parameter

the program is supposed to use

(define (sum f n)
  (if (= n 0)
      (f 1)
      (+ (f n) (sum f (- n 1)))))
(define (harm-term k)
  (/ 1 k))
(define (harm-sum n)
  (sum (harm-term 1) n))

to create a function called harm-sum that calculates the sum of harmonic series. But I keep getting the error application:

    not a procedure;
     expected a procedure that can be applied to arguments

  given: 3
  arguments...:

for the sum function.

Upvotes: 3

Views: 60

Answers (1)

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

(define (sum f n)
  (if (= n 0)
      (f 1)
      (+ (f n) (sum f (- n 1)))))
(define (harm-term k)
  (/ 1 k))
(define (harm-sum n)
  (sum (harm-term 1) n))

The way that you are eventually calling sum is wrong because you call sum with (harm-term 1) as the parameter that you are expecting a function for. (harm-term 1) clearly evaluates to a 1.

This means that when it is used later in sum as the parameter f it makes no sense (i.e. you eventually call (1 1))

You should be doing something like this:

(define (sum f n)
  (if (= n 0)
      (f 1)
      (+ (f n) (sum f (- n 1)))))
(define (harm-term k)
  (/ 1 k))
(define (harm-sum n)
  (sum harm-term n)) ; the difference is the function itself is passed instead of the value the function returns for 1

Upvotes: 2

Related Questions