The Ackermann function
Haskell, 35
0%n=1+n
m%n=iterate((m-1)%)1!!(n+1)
this defines the operator function %
.
this works by noticing that m%n
(where a
is the ackerman function) for nonzero m
is (m-1)%
applied n+1
times to 1
. for example, 3%2
is defined as 2%(3%1)
which is 2%(2%(3%0))
, and this is 2%(2%(2%1))
GolfScript (30)
{1$1>{1\){1$(\A}*\;}{+)}if}:A;
Online demo
Without the 1>
(which special-cases A(1, n)
) it takes 9 minutes to compute A(3, 10)
on the computer I've tested it on. With that special case it's fast enough that the online demo takes less than 10 seconds.
Note that this isn't a naïve translation of the definition. The recursion depth is bounded by m
.
Dissection
{ # Function boilerplate
1$ # Get a copy of m: stack holds m n m
1>{ # (Optimisation): if m is greater than 1
1 # Take this as the value of A(m, -1)
\){ # Repeat n+1 times:
# Stack: m A(m, i-1)
1$(\ # Stack: m m-1 A(m, i-1)
A # Stack: m A(m, i)
}*
\; # Lose that unwanted copy of m
}{ # Else
+) # A(m in {0, 1}, n) = m + n + 1
}if
}:A; # Function boilerplate
Binary lambda calculus, 54 bits = 6.75 bytes
Hexdump:
00000000: 1607 2d88 072f 68 ..-../h
Binary:
000101100000011100101101100010000000011100101111011010
This is λm. m (λg. λn. g (n g 1)) (λn. λf. λx. f (n f x)), where all numbers are represented as Church numerals.