Skip to main content
Code Review

Return to Question

edited tags
Link
AJNeufeld
  • 35.2k
  • 5
  • 41
  • 103
Bounty Ended with no winning answer by Community Bot
added 148 characters in body
Source Link
Landei
  • 7k
  • 2
  • 25
  • 34

[Clarification]

With "iterative solution" I mean the algorithm described here: http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution

[Clarification]

With "iterative solution" I mean the algorithm described here: http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution

Bounty Started worth 50 reputation by Landei
Tweeted twitter.com/#!/StackCodeReview/status/57095399579729920
Source Link
Landei
  • 7k
  • 2
  • 25
  • 34

Towers of Hanoi in Haskell

Of course the recursive version is trivial:

hanoi n = solve n 1 2 3
solve 0 _ _ _ = []
solve n from help to = (solve (n-1) from to help) ++ [(from,to)] ++ (solve (n-1) help from to)

However my iterative version looks terrible with a lot of code repetition:

hanoi n = map rep $ solve [1..n] [] [] where
 rep (x,y) | odd n = ([1,3,2] !! (x-1), [1,3,2] !! (y-1))
 | otherwise = (x,y) 
 
solve from help to = head $ mapMaybe ready $ iterate step (from,help,to,[]) where
 step (1:xs,ys,zs,sol) = let (xs',zs',sol') = try xs zs 1 3 ((1,2):sol)
 in (xs',1:ys,zs',sol')
 step (xs,1:ys,zs,sol) = let (xs',ys',sol') = try xs ys 1 2 ((2,3):sol)
 in (xs',ys',1:zs,sol')
 step (xs,ys,1:zs,sol) = let (ys',zs',sol') = try ys zs 2 3 ((3,1):sol)
 in (1:xs,ys',zs',sol')
 try [] [] _ _ sol = ([],[], sol) 
 try (x:xs) [] a b sol = (xs,[x], (a,b):sol) 
 try [] (y:ys) a b sol = ([y],ys, (b,a):sol) 
 try (x:xs) (y:ys) a b sol | x < y = (xs,x:y:ys, (a,b):sol)
 | y < x = (y:x:xs,ys, (b,a):sol) 
 ready ([],[],_,sol) = Just $ reverse sol
 ready ([],_,[],sol) = Just $ reverse sol
 ready _ = Nothing

Any ideas? More general, how to deal with situations like this where you have a lot of different cases and args?

lang-hs

AltStyle によって変換されたページ (->オリジナル) /