0

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.

3
  • 1
    btw: I think this is the 3rd or 4th question on this in the last couple of days - is there a MOOC or something that has this as an exercise? Commented May 6, 2015 at 16:16
  • 1
    A rather trivial observation, move must extract elements from the list [Move] (perhaps according to some yet not all situations), in order to ensure the base case of empty list holds at some point, and thus ensure termination of the game. Commented May 6, 2015 at 16:18
  • 1
    yes. Carsten, we are having a class in LMU. Commented May 6, 2015 at 16:38

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

1 Comment

@bheklilr "this requires taking apart a tuple then constructing a new one exactly like it" - Correct me if I'm wrong but this is something I would expect the compiler to optimise away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.