Here are some snippets in different languages.
Function double in question is taken from SICP, ex. 1.41.
Lisp:
(define (double f) (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
(((double (double double)) inc) 5)
Python:
def double(f):
def result(x):
return f(f(x))
return result
def inc(x):
return x + 1
double(double(double(inc)))(5)
Javascript:
var double = function(f) {
return function(x) { return f(f(x)) };
};
var inc = function(x) { return x + 1 };
(double(double(double(inc))))(5);
Ruby:
double = lambda {|f| lambda {|x| f[f[x]] } }
inc = lambda {|x| x+1 }
double[double[double[inc]]][5]
If I am not insane, these functions should do the same thing and return the same result.
However, lisp version returns 21 whereas others return 13. Can you explain that difference to me? Am I missing something?
How you call the functions in the scheme code is different from the others. The equivalent python would be:
In words, the scheme code creates a function that applies another function 16 times, and applies that function to
inc. The python creates functions that applyinc8 times; the others work the same as the python.The difference might be a bit clearer if you introduce names for the intermediate steps. In scheme:
I hope that’s correct syntax; it’s been a while since I’ve done anything with scheme.
In python: