Anthony
Anthony

Reputation: 51

A recursive function "game" in Haskell

I don't quite understand the following code:

game :: ([Move], Towers) -> Towers
game ([], towers) = towers
game situation = game (move situation)

situation here has never mentioned in any part of the codes (there are a long code before this, called the tower of Hanoi, I suppose a lot of people here know it). Why can we directly use situation here? I know this is correct and the code works very well, but I don't know why.

Upvotes: 0

Views: 93

Answers (1)

bheklilr
bheklilr

Reputation: 54068

situation is an argument to the function game. It would have the type ([Move], Towers). Essentially, what you're saying is "if situation has no moves then return the towers, otherwise perform a move and then pass that result to game".

It would be perfectly legal to write this function as

game ([], towers) = towers
game (moves, towers) = game (move (moves, towers))

But this requires taking apart a tuple then constructing a new one exactly like it, or you could use any other name for this value:

game ([], towers) = towers
game foobar = game (move foobar)

It's nothing more than a name for the argument to the function game, what it's actually called isn't important (so long as it's not a reserved keyword, of course, you couldn't name it import, for example).

Upvotes: 4

Related Questions