Scala exercise with types and abstraction

Write an API for playing tic-tac-toe. There should be no side-effects (or variables), at all, for real. The move function will take a game state, a Position and it will return a data type that you write yourself.

The following functions (at least) must be supported:

  1. move (as mentioned)
  2. whoseTurn (returns which player’s turn it is)
  3. whoWon (returns who won or if a draw)
  4. playerAt (returns which player, if any, is at a given position)

Importantly, the following must be true:

  1. It is a compile-time error to call move or whoseTurn on a game that has been completed
  2. It is a compile-time error to call whoWon on a game that has not been completed
  3. The playerAt function must be supported on both complete and in-play games

Good luck and may the types be with you.

6 Responses to “Scala exercise with types and abstraction”

  1. Scala exercise with types and abstraction Says:

    [...] a data type that you write yourself. The following functions (at least) must be supported:… [full post] Tony Morris λ Tony’s blog λ programming 0 0 0 0 [...]

  2. Twitter Trackbacks for λ Tony’s blog λ » Blog Archive » Scala exercise with types and abstraction [tmorris.net] on Topsy.com Says:

    [...] λ Tony’s blog λ » Blog Archive » Scala exercise with types and abstraction blog.tmorris.net/scala-exercise-with-types-and-abstraction/ – view page – cached Write an API for playing tic-tac-toe. There should be no side-effects, at all, for real. The move function will take a game state, a Position and it will return a data type that you write yourself. [...]

  3. Angel Says:

    Hi, here is my solution (with small extras, so you can also play it):

    https://gist.github.com/771842

    What do you think about it?

  4. λ Tony’s blog λ » Blog Archive » Critique of Odersky’s Scala levels Says:

    [...] recently gave a beginner API design quiz. I use it in programming classes that I teach, where many people struggle with it. When these [...]

  5. Berlin Brown Says:

    Angel, nice example.

    For Tony, could you do an experiment with a toy language. “Write a toy language that has the following rules…”

  6. Type safe data structures with “invalid” states | Dev Portal Says:

    [...] read the delightful article on a type safe tic-tac-toe API recently. It got me thinking how one might do this for an application with a complex GUI and data [...]

Leave a Reply