Reputation: 715
I'm studying SICP, and I didnt exactly get the idea behind function return.
(define (deriv g)
(lambda (x)
(/ (- (g (+ x dx)) (g x))
dx)))
Code above will be used as ((deriv square) 10), why cant we just make this code simpler? By evaluating the result in 1 step?
(define (deriv g x)
(/ (- (g (+ x dx)) (g x))
dx))
Why do we REALLY need function as returned value? Abstraction? Partial application? I guess there is a much more simpler and clearer idea, what do we need it for, and WHERE to use it. Thanks!
Upvotes: 2
Views: 126
Reputation: 71065
Consider (let ((dsq (deriv square))) (map dsq (range 0 100 0.1)))
vs. (map (lambda (x) (deriv square x)) (range 0 100 0.1))
.
Partial application in the first snippet pre-computes something, which the second code must redo at each x
, again and again, which is wasteful.
Upvotes: 0
Reputation:
Well, in this case because mathematically the derivative of a function is a function. So if you want a function which computes the derivative of a function then it's going to return a function.
And this is useful. Imagine if you have a function called fplot
which will plot a function between two values. Then I can plot the function sin
with
(fplot sin (- pi) pi)
Say. Now if I want to plot the derivative of sin
(let's imagine I didn't know it was cos
), I can plot that:
(fplot (deriv sin) (- pi) pi)
fplot
doesn't need to know anything at all about where the function it's plotting came from. The alternative would be to write a special function to plot the derivative of a function, and then perhaps another one to plot the second derivative and so on, and then eventually some function which takes a function and an integer and plots that order of derivative of it or something.
And then you'd realise that, well, wouldn't it be better design to have a function whose job was to plot functions and another function whose job was to compute the functions which are the derivatives of functions, and then these things would compose together nicely.
Upvotes: 7