I've written a TLA+ spec of the Towers of Hanoi problem:
TEX
ASCII
------------------------------- MODULE Hanoi -------------------------------
EXTENDS Sequences, Integers
VARIABLE A, B, C
CanMove(x,y) == /\ Len(x) > 0
/\ IF Len(y) > 0 THEN Head(y) > Head(x) ELSE TRUE
Move(x,y,z) == /\ CanMove(x,y)
/\ x' = Tail(x)
/\ y' = <<Head(x)>> \o y
/\ z' = z
Invariant == C /= <<1,2,3>> \* When we win!
Init == /\ A = <<1,2,3>>
/\ B = <<>>
/\ C = <<>>
Next == \/ Move(A,B,C) \* Move A to B
\/ Move(A,C,B) \* Move A to C
\/ Move(B,A,C) \* Move B to A
\/ Move(B,C,A) \* Move B to C
\/ Move(C,A,B) \* Move C to A
\/ Move(C,B,A) \* Move C to B
=============================================================================
The TLA Model checker will solve the puzzle for me when I specify the Invariant
formula as an Invariant.
I want to make it a bit less verbose though, ideally I don't want to pass in the unchanged variable to Move()
, but I can't figure out how. What I want to do is to write
Move(x,y) == /\ CanMove(x,y)
/\ x' = Tail(x)
/\ y' = <<Head(x)>> \o y
/\ UNCHANGED (Difference of and {A,B,C} and {y,x})
How can I express that in the TLA language?
Instead of variables A, B, C, you should have a single sequence, towers
, where the towers are indexes. This would also have the advantage of being generic in the number of towers. Your Next
formula would be shorter, too:
CanMove(i,j) == /\ Len(towers[i]) > 0
/\ Len(towers[j]) = 0 \/ Head(towers[j]) > Head(towers[i])
Move(i, j) == /\ CanMove(i, j)
/\ towers' = [towers EXCEPT ![i] = Tail(@),
![j] = <<Head(towers[i])>> \o @]
Init == towers = << <<1,2,3>>, <<>>, <<>> >> \* Or something more generic
Next == \E i, j \in DOMAIN towers: i /= j /\ Move(i, j)
Alternatively, if you want to continue using letters, you can use a record instead of a sequence for towers
, and all you need to change in my suggested spec is:
Init == towers = [a |-> <<1, 2, 3>>, b |-> <<>>, c |-> <<>>]