views:

122

answers:

2

Hey,

In SICP 1.2.1 there is a function that makes a rational number, as follow:

(define (make-rat n d)
  (let ((g (gcd n d)))
    (cons (/ n g) (/ d g))))

I'm just curious how you can implement the same thing using lambda instead of let, without calling GCD twice. I couldn't figure it out myself.

+7  A: 

These two things are same:

((lambda (p1 p2...) body) v1 v2...)

and

(let ((p1 v1) (p2 v2)...) body)
Amadan
+6  A: 

Looking at SICP section 1.3.2,

(let ((<var1> <exp1>)
      (<var2> <exp2>)
      ...
      (<varn> <expn>))
   <body>)

is equivalent to

((lambda (<var1> ...<varn>)
    <body>)
 <exp1>
 ...
 <expn>)

So your procedure,

(define (make-rat n d)
  (let ((g (gcd n d)))
    (cons (/ n g) (/ d g))))

should be equivalent to

(define (make-rat n d)
  ((lambda (g)
    (cons (/ n g) (/ d g)))
  (gcd n d)))

(Sorry, I don't have a Scheme interpreter in front of me to test this with.)

Bill the Lizard
Not quite: your last `define` is missing a pair of parens to make it work: `((lambda (g) ...) (gcd n d))` (you have the closing one, but are missing the opening paren if I count right)
Dirk
@Dirk: Thanks for pointing out the imbalance. I can't even write 4 lines of code without a proper editor that knows Scheme. :)
Bill the Lizard