Search code examples
lambdaschemesicp

using lambda instead of let in scheme


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.


Solution

  • 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)))