Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 806
CamelCamelCamel Avatar asked May 25 '10 16:05

CamelCamelCamel


People also ask

What is the point of lambda in scheme?

Lambda is the name of a special form that generates procedures. It takes some information about the function you want to create as arguments and it returns the procedure. It'll be easier to explain the details after you see an example.

How does let work in Scheme?

In Scheme, you can use local variables pretty much the way you do in most languages. When you enter a let expression, the let variables will be bound and initialized with values. When you exit the let expression, those bindings will disappear.

How do you call a function in Scheme?

A function call is written as (f args) where f is the name of the function and args a space-separated sequence of arguments. So to call tab without arguments, you'd write (tab) and to call translate with the argument x , you'd write (translate x) .


1 Answers

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)))
like image 54
Bill the Lizard Avatar answered Oct 06 '22 02:10

Bill the Lizard