Why does this racket function need an argument? And how does it work?

I am a beginner in Racket and the following code is from University of Washington's Racket Programming course-

(define s "hello")
(define (pow1 x y)
  (if(= y 0)
     1
     (* x (pow1( - y 1)))))

(define pow2
  (lambda(x)
    (lambda(y)
      (pow1 x y))))
(define three (pow2 3))

From what I have read, for arguments to be passed in Racket the format should be -

(define (id id id) expression)

Why does it not hold true for three? And how exactly does three work?

EDIT1- When I run (pow1 1 2) I get an error saying that number of arguments given is 1, and when I write (pow1 2 3 4) it says number of arguments is 3. What is going on?

Upvotes: 1

Views: 76

Answers (1)

melpomene
melpomene

Reputation: 85757

(define pow2
  (lambda(x)
    (lambda(y)
      (pow1 x y))))

This defines pow2 as a lambda expression of some kind.

(define three (pow2 3))

This defines three as the result of (pow2 3). What is (pow2 3)? Well, let's inline the value of pow2:

(pow2 3)
; inline pow2
((lambda(x)
   (lambda(y)
     (pow1 x y)))
  3)

Applying a lambda (of a parameter x) to a value (such as 3) substitutes the value in the body of the lambda (i.e. we can replace x by 3):

(lambda(y)
  (pow1 3 y))

Now this is the value of three.

Doing (three 2) proceeds like this:

(three 2)
; inline three
((lambda(y)
   (pow1 3 y))
  2)
; apply lambda
(pow1 3 2)

... and from there on it's just a call to pow1.

Upvotes: 3

Related Questions