Skip to content

Instantly share code, notes, and snippets.

@dmgottlieb
Created July 15, 2015 18:43
Show Gist options
  • Save dmgottlieb/56369e01521c61dd00b6 to your computer and use it in GitHub Desktop.
Save dmgottlieb/56369e01521c61dd00b6 to your computer and use it in GitHub Desktop.
4-tower Tower of Hanoi solutions using μ-recursion in Haskell
import Data.List
import Data.Ord
-- Tower of Hanoi implementation
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi 0 a b c = [ ]
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a
-- Tower of Hanoi with 4 pegs.
hanoi4 :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move]
hanoi4 0 a b c d = [ ]
hanoi4 1 a b c d = [(a, b)]
hanoi4 n a b c d = shortest [(hanoi4 (n - k) a d c b ++ hanoi k a b c ++ hanoi4 (n - k) d b a c) | k <- [1..(n-1)]]
shortest :: [[a]] -> [a]
shortest [] = []
shortest ls = minimumBy (comparing length) ls
@dmgottlieb
Copy link
Author

On reflection, i think this isn't really μ-recursion. Minimization over finite arguments can be done w/ primitive recursion IIRC.

@rebornwwp
Copy link

very helpful.

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