Skip to content

Instantly share code, notes, and snippets.

@simonneutert
Created October 1, 2022 17:14
Show Gist options
  • Save simonneutert/a3fec8d8c9d45ebac61f6b3c36461c69 to your computer and use it in GitHub Desktop.
Save simonneutert/a3fec8d8c9d45ebac61f6b3c36461c69 to your computer and use it in GitHub Desktop.
Towers of Hanoi in Clojure
(defn hanoi [n left middle right]
(cond
(> n 5) (throw (Exception. "No way! This would run far too long!"))
(= n 1) (println "Move disc" n "from" left "to" right)
:else (do (hanoi (dec n) left right middle)
(println "Move disc" n "from" left "to" right)
(hanoi (dec n) middle left right))))
(hanoi 5 :left :middle :right)
(defn towers-of-hanoi-lazy [n from to via]
(when (pos? n)
(lazy-cat
(towers-of-hanoi (dec n) from via to)
(cons [from '-> to]
(towers-of-hanoi (dec n) via to from)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment