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.
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.
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.
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) .
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With