Reputation: 2520
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?
Upvotes: 0
Views: 308
Reputation: 363
I would like to do like this way even though my method is nor recursive as well.
allllmove :: Towers -> Towers
allmove ([0],[0],[0]) = ([0],[0],[0])
allmove ((x:xs),y,z)
length(x:xs) > length z && length z > length y = (xs,(x:y),z)
length(x:xs) >= length z && length (x:xs) > length y = (xs,(x:y),z) ... .. .
Upvotes: 0
Reputation: 1282
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.
Upvotes: 1