Session Ready
Exercise

Make it Classy (1)

As well as simply retrieving the class, the class() function can be used to override it. The syntax is

class(x) <- "some_class"

This is particularly useful for lists, since lists can be used to combine other variables into more complex variables. (Remember the Lego analogy: individual variables are like Lego pieces, and you can use lists to build whatever you like.)

In this exercise, you'll look at an object to store the state of a chess game, and override its class.

To make sense of the exercise, you need to know a little bit about chess.

  • There are two players in a chess game, named "white" and "black".
  • Each player has six types of piece: a king, a queen, bishops, knights, rooks, and pawns.
  • The position of each piece can be recorded using the row ("a" to "h") and the column (1 to 8).
Instructions
100 XP

The list variable chess has been predefined in your workspace.

  • Explore chess to understand its structure.
  • Override the class of chess to be "chess_game".
  • Check whether or not chess is still a list, using is.list().
  • Determine the number of pieces still left on the board.
    • A good approach is to flatten the object using unlist() and return its length().