Skip to content

Instantly share code, notes, and snippets.

@mausch
Created May 25, 2012 22:45
Show Gist options
  • Save mausch/2790981 to your computer and use it in GitHub Desktop.
Save mausch/2790981 to your computer and use it in GitHub Desktop.
Church-encoded numbers as a measure of 'how functional is a language' http://stackoverflow.com/a/6166222/21239
# Careful with the spaces!
thrice = (f) -> (x) -> f(f(f(x)))
_3 = thrice((x) -> x + 1) 0
_9 = thrice(thrice((x) -> x + 1)) 0
_27 = (thrice thrice)((x) -> x + 1) 0
Func<A,A> thrice<A>(Func<A,A> f) {
return x => f(f(f(x)));
}
var _3 = thrice<int>(x => x + 1)(0);
var _9 = thrice(thrice<int>(x => x + 1))(0);
var _27 = thrice<Func<int, int>>(thrice)(x => x + 1)(0);
let thrice f = f >> f >> f
let _3 = thrice ((+) 1) 0
let _9 = (thrice (thrice ((+) 1))) 0
let _27 = ((thrice thrice) ((+) 1)) 0
thrice f = f . f . f
_3 = thrice (+1) 0
_9 = (thrice $ thrice (+1)) 0
_27 = (thrice thrice $ (+1)) 0
function thrice(f) {
return function(x) {
return f(f(f(x)));
};
}
var _3 = thrice(function(x) { return x + 1; })(0);
var _9 = thrice(thrice(function(x) { return x + 1; }))(0);
var _27 = thrice(thrice)(function(x) { return x + 1; })(0);
def thrice(f):
return lambda x: f(f(f(x)))
_3 = thrice(lambda x: x + 1)(0)
_9 = thrice(thrice(lambda x: x + 1))(0)
_27 = thrice(thrice)(lambda x: x + 1)(0)
// http://stackoverflow.com/questions/6166155/is-scala-a-functional-programming-language#comment7166328_6166222
def thrice[A](f: A => A) = f andThen f andThen f
val _3 = thrice[Int](1+)(0)
val _9 = thrice(thrice[Int](1+))(0)
val _27 = thrice(thrice[Int])(1+)(0)
@; http://stackoverflow.com/a/6166222/21239
(define (thrice f)
(lambda (x)
(f (f (f x)))))
(define _3 ((thrice 1+) 0))
(define _9 ((thrice (thrice 1+)) 0))
(define _27 (((thrice thrice) 1+) 0))
@mausch
Copy link
Author

mausch commented May 25, 2012

Church-encoded numbers as a measure of 'how functional is a language' http://stackoverflow.com/a/6166222/21239

Not sure this really measures how functional a language is, but it certainly shows how first-class functions are in different languages. Plus, it's fun :)

Found a mistake? Want to improve something or add another language? Let the forking begin :)

@guilleiguaran
Copy link

thrice = fn(f) -> fn(x) -> x |> f.() |> f.() |> f.() end end
_3 = thrice.(fn(x) -> x + 1 end).(0)
_9 = thrice.(thrice.(fn(x) -> x + 1 end)).(0)
_27 = thrice.(thrice).(fn(x) -> x + 1 end).(0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment