by simias · 5y ago · 0 comments
#include <stdio.h>
#define DX 0.0001
#define DERIV(_f) float deriv_##_f(float x) { return (_f(x + DX) - _f(x)) / DX; }
float cube(float x) { return x * x * x; }
DERIV(cube)
int main(void) {
printf("%f\n", deriv_cube(2));
printf("%f\n", deriv_cube(3));
printf("%f\n", deriv_cube(4));
}
Any language supporting closures or generics could get rid of the unsexy DERIV macro.What sets Lisp apart is its "code as data" approach which lets the coder write incredibly powerful macro (and also incredibly hard to understand code). The rest can easily be emulated in other languages.
I do like this naive approach mind you, there's a certain Zen to be found reimplementing these mathematical concepts from first principles, I just really fail to see what makes Lisp so remarkable in this context.
I'm not sure how you would do that in C, other than by Greenspunning up an implementation of first-class functions.
C's preprocessor is very powerful and like the rest of the language it can be used to shoot yourself in the foot - but that doesn't mean you shouldn't take full advantage of it or that actually taking advantage of it instead of treating it as a poor man's module system is "abusing" it.
double fprime(double (*f)(double), double x);
but you wouldn't be able to define double (*deriv(double (*f)(double)))(double);
as C does not support closures.Meanwhile, in C++ you might use
std::function<double(double)> deriv(std::function<double(double)> f);I really wouldn’t have got this stuff 5 years ago but functions returning functions is a super sweet tool and I’m glad it’s finally seeing mainstream adoption. It’s a small leap from the imperative mindset but results in much neater flows when done well.
If you're going to claim it is different, then I claim that LISP can't do addition. When you have (+ 1 1) that is something completely different, because you have the syntax fucked up. It's not addition like I know it, so it doesn't count.
And also, it has nothing to do with the syntax (+ 1 1), the keyword is homoiconicity.