David542
David542

Reputation: 110552

Scheme define a lambda

I have the following function to compute the sum from A to B of a function in scheme:

(define (SUM summation-function A increment-function B)
  (if (> A B)
      0
      (+ (summation-function A)
         (SUM
           summation-function (increment-function A) increment-function B))))

Currently I define two procedures before calling the function, for example:

(define (self x) x)     ; do nothing, just sum itself
(define (inc x) (+ x 1)); normal +1 increment
(SUM self 0 inc 5)

How instead could I just define the procedure in the call itself, for example:

; in pseudocode
(SUM, lambda x: x, 0, lambda x: (+ x 1), 5)

Upvotes: 0

Views: 62

Answers (2)

Sylwester
Sylwester

Reputation: 48775

You can rewrite your definitions like this:

(define self 
  (lambda (x) 
    x))

(define inc 
  (lambda (x) 
    (+ x 1)))

Now you haves split up creating the variable self and inc and the lambda syntax that creates a closure. It is EXACTLY the same as what you wrote in your question.

By substitution rules you should be able to replace a variable with the expression in its definition:

(SUM self 0 inc 5)

;; is the same as
(SUM (lambda (x) 
        x)
     0
     (lambda (x) 
        (+ x 1))
     5)

Please note that older Scheme reports wasn't case sensitive, but SUM and sum are two different names in later reports. It is also common to use lower space letters for variables and procedure names are, as I showed earlier, variables. This is why the procedure list stops working when you define a value to the variable list. One namespace to rule them all.

Upvotes: 2

Óscar López
Óscar López

Reputation: 236150

Typically, we'd use lambdas like this:

(SUM (lambda (x) x) 0 (lambda (x) (+ x 1)) 5)

For the above example in particular, some Scheme interpreters already provide built-in procedures that do precisely what you want and we can simply say:

(SUM identity 0 add1 5)

Upvotes: 1

Related Questions