Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Ackermann function(s) in GAWK (fun!)

49 views
Skip to first unread message

Kenny McCormack

unread,
Dec 20, 2014, 1:39:05 PM12/20/14
to
No bug or question in this post - just some fun stuff. Consider:

--- Cut Here ---
#!/bin/gawk4 -f
function A0(m,n,p) {
switch (p) {
case 0:
return m + n
case 1:
case 2:
if (n == 0) return p - 1
break
default:
if (n == 0) return m
}
return A0(m, A0(m, n-1, p), p - 1)
}

function A1(m,n) {
if (m == 0) return n + 1
if (n == 0) return A1(m - 1, 1)
return A1(m - 1, A1(m, n - 1))
}

$1 == "A0" && NF == 4 { print A0($2,$3,$4);next }
$1 == "A1" && NF == 3 { print A1($2,$3);next }
{ print "Invalid first arg or wrong # of args!" }
--- Cut Here ---

These are two "Ackermann" functions. I got the code more or less directly
from Wikipedia. The first one is (so it says) the original function by
Ackermann, the second is the more famous one - the one that is generally
refered to as "the" Ackermann function. Not much is known about the first
one, but for the second, there is a table in Wikipedia giving correct results
of the function for various small inputs.

A couple of notes:

1) Calculating A1(4,1) using GAWK 3.1.4 caused it to crank for about 15
minutes then exit from GAWK (with no error message). Calculating
it in GAWK4 (4.1.1) caused it crank for about 52 minutes before
generating the correct answer of 65533 (aka, 2^16-3).

2) I actually got to use the "switch" statement in GAWK! This is the
first time I've ever actually had a useful use for this feature of
the GAWK language. I'm so pleased...

--
"Although written many years ago, Lady Chatterley's Lover has just
been reissued by the Grove Press, and this fictional account of the
day-to-day life of an English gamekeeper is still of considerable
interest to outdoor minded readers, as it contains many passages on
pheasant raising, the apprehending of poachers, ways to control vermin,
and other chores and duties of the professional gamekeeper.

"Unfortunately, one is obliged to wade through many pages of extraneous
material in order to discover and savor these sidelights on the
management of a Midlands shooting estate, and in this reviewer's opinion
this book cannot take the place of J.R. Miller's Practical Gamekeeping"
(Ed Zern, Field and Stream, November 1959, p. 142).
0 new messages