Cam
Cam

Reputation: 15244

Scheme define/lambda shorthand

In Scheme, how can I make use of the define/lambda shorthand for nested lambda expressions within my define?

For example given the following procedure...

(define add
  (lambda (num1 num2)
    (+ num1 num2)))

One can shorten it to this:

(define (add num1 num2)
  (+ num1 num2))


However, how can I shorten the following function similarly ?

(define makeOperator
  (lambda (operator)
    (lambda (num1 num2)
      (operator num1 num2))))

;example useage - equivalent to (* 3 4):
((makeOperator *) 3 4)

Upvotes: 6

Views: 5754

Answers (3)

Michał Marczyk
Michał Marczyk

Reputation: 84379

Some implementations of Scheme -- like Guile (tested with version 1.8) and MIT Scheme -- provide the following shorthand notation:

(define ((foo x) y) (+ x y))

(foo 5)
; => procedure
((foo 5) 3)
; => 8

I believe this notation is used quite a lot in Structure and Interpretation of Classical Mechanics.

Upvotes: 7

Eli Barzilay
Eli Barzilay

Reputation: 29554

Contrary to the above answer, the second lambda can use the shorthand define notation:

(define (makeOperator operator)
  (define (foo num1 num2)
    (operator num1 num2))
  foo)

Upvotes: 4

sepp2k
sepp2k

Reputation: 370445

(define (makeOperator operator)
  (lambda (num1 num2)
    (operator num1 num2)))

The second lambda can not be shortened.

Well you could shorten it to (define (makeOperator operator) operator), if you don't want to enforce that the returned function takes exactly two arguments.

Upvotes: 12

Related Questions