Search code examples
algorithmhaskellrecursionpattern-matchingtowers-of-hanoi

Recursive function in haskell


I am trying to solve some issues with programming in haskell.

I am having this three types and the Hanoi-algorithm:

type Position = Int
type Move = (Position,Position)
type Towers = ([Int],[Int],[Int])

hanoi 1 i j = [(i,j)]
hanoi n i j = hanoi n' i otherT ++ [(i,j)] ++ hanoi n' otherT j
    where      
            n' = n-1
            otherT = 1+2+3-i-j -- other tower

Now I wrote a function with makes one single MOVE.

move ::([Move],Towers) -> ([Move],Towers) 
move ::([Move],Towers) -> ([Move],Towers)
move ([],(xs,ys,zs) ) = ((error "Error"),(xs,ys,zs) )
move (((a,b): tail), (xs,ys,zs) )
              | a > 3 =    (tail, ((error "Error"),ys,zs) )                
              | b > 3 =    (tail, ((error "Error"),ys,zs ) )                
              | otherwise = hilfsfunktion (((a,b): tail), (xs,ys,zs) )



hilfsfunktion (((1,2): tail), ((x:xs),(y:ys),zs) ) 
            | x < y = (tail, (xs, (x:y:ys),zs) )
            | x > y = (tail, (xs, (error "too big"),(error "too big")))
hilfsfunktion (((1,2): tail), ((x:xs), [],zs) ) = (tail, (xs, x:[],zs) )

The function is much longer, but you can see that I solved this with Pattern Matching.

Now I try to write a function, that called this "move"-function as long as the list is not empty. So at first I used Pattern Matching for the case, that the list is empty.

all_moves:: ([Move], Towers) -> Towers
all_moves ([],(xs,ys,zs) ) = (xs,ys,zs)
all_moves (((a,b): tail), (xs,ys,zs) ) = ????

Now I need some help, in Java I would use a loop to fix this. I think I have to call the function "move" recursive, but I don't know how to to this. How can I solve this function?


Solution

  • I'm not sure exactly how your hanoi solution works, but I think this answers your question:

    all_moves :: ([Move], Towers) -> Towers
    all_moves ([], (xs, ys, zs)) = (xs, ys, zs)
    all_moves movetowers         = all_moves (move movetowers)
    

    Hopefully you can see why this works - we keep doing a move and then a recursive call until there are no moves left.