Reputation: 19
I am trying to create a Scheme function.
I created this piece of code but I keep getting errors:
(define (slope-of-line p1 p2)
(let ((m (/ (- (cdr p2) (cdr p1))
(- (car p2) (car p1))))
(b (- (cdr p1)
(* m (car p1)))))
(lambda (x) (+ (* m x) b))))
Thank you!
Upvotes: 0
Views: 378
Reputation: 48735
It seems ok, but I notice you are trying to use m
in the expression of the binding b
. At the time of that expression m
doesn't exist. If you wonder why you can translate the let into a anonymous function call it is syntax sugar for:
((lambda (m b)
(lambda (x) (+ (* m x) b)))
(/ (- (cdr p2) (cdr p1)) (- (car p2) (car p1)))
(- (cdr p1) (* m (car p1))))
Here you clearly see that m
is used outside of the lambda that defines it.
Your code can be fixed by replacing let
with let*
.
(define (slope-of-line p1 p2)
(let* ((m (/ (- (cdr p2) (cdr p1))
(- (car p2) (car p1))))
(b (- (cdr p1)
(* m (car p1)))))
(lambda (x) (+ (* m x) b))))
(define slope (slope-of-line '(1 . 3) '(6 . 4)))
(slope 20) ; ==> 34/5 (which is close to ~6,8)
The reason why this works is because let*
is just syntax sugar for nested let
:
(let* ((a a-expression)
(b b-expression))
body ...)
Is the same as:
(let ((a a-expression))
(let ((b b-expression))
body ...))
Upvotes: 2