Skip to content

Instantly share code, notes, and snippets.

@methylene
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save methylene/d70a9610ac7c1608af75 to your computer and use it in GitHub Desktop.
Save methylene/d70a9610ac7c1608af75 to your computer and use it in GitHub Desktop.
;; A version of the ackermann function, described in https://u.osu.edu/friedman.8/files/2014/01/LongFinSeq98-2f0wmq3.pdf
(require '[clojure.core.match :refer [match]])
(defn ackermann [[k & r :as s] n]
(if (not (seq s))
n
(match [k n]
[1 _] (recur r (*' 2 n))
[_ 1] (recur (cons (dec k) r) 1)
[_ _] (recur (cons k (cons (dec k) r))
(dec n)))))
;; (ackermann '(3) 5)
;; some optimization
(defn exp [n]
(loop [n n r 2]
(if (= n 1)
r
(recur (dec n) (*' 2 r)))))
(defn tetr [n]
(loop [n n r 2]
(if (= n 1)
r
(recur (dec n) (exp r)))))
(defn ackermann' [[k & r :as s] n]
(if (not (seq s))
n
(match [k n]
[1 _] (recur r (*' 2 n))
[2 _] (recur r (exp n))
[3 _] (recur r (tetr n))
[_ 1] (recur r 2)
[_ 2] (recur r 4)
[_ _] (recur (cons k (cons (dec k) r))
(dec n)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment