Menu
Coddy logo textTech

Books and Members

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 50 of 57.

In this project you build the core of a library system with Reference Classes, because books and members change while the program runs: a book is lent and returned, a member's list of loans grows and shrinks. A Library object receives commands, one per line, and replies to each. Over five steps it learns to add books and members, lend and take back books, search the catalogue and print a report.

ADD_BOOK 1 Dune
JOIN ada
BORROW ada 1
RETURN ada 1
SEARCH dune
REPORT

The program has one class per file. Book.R and Member.R hold the two small classes, and Library.R holds the class that stores them in two named lists and answers the commands. Because RC objects are references, changing a book that was looked up in the list changes the book in the library:

Book <- setRefClass("Book", fields = list(id = "numeric", title = "character", borrower = "character"))
books <- list()
books[["7"]] <- Book$new(id = 7, title = "Dune")
b <- books[["7"]]
b$borrower <- "ada"
cat(books[["7"]]$borrower, is.null(books[["9"]]))

Output:

ada TRUE

handle(line) splits the command and uses switch() on its first word to call the method for that command. Every method returns its replies as a character vector, so a command such as REPORT can reply with several lines. A title can contain spaces, so it is everything after the id:

p <- strsplit("ADD_BOOK 7 The Hobbit", " ")[[1]]
id <- as.numeric(p[2])
title <- paste(p[-(1:2)], collapse = " ")
cat(id, title, sep = ": ")

Output:

7: The Hobbit
challenge icon

Challenge

Easy

The classes Book (fields id, title, borrower) and Member (fields name, borrowed) are given. Complete two methods of Library in Library.R:

  • add_book(id, title) for ADD_BOOK <id> <title>: store a new book under as.character(id) and reply added book 1: Dune; when the id is taken reply book 1 exists.
  • join(name) for JOIN <name>: store a new member under the name and reply welcome ada; when the name exists reply ada is already a member.

The supplied code sends every input line to lib$handle(line) and prints each returned reply on its own line. Member names are single lower-case words, book ids are whole numbers, and the input holds only the commands described so far. Any other command replies unknown command.

Your code goes in Book.R, Member.R and Library.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Book.R")
source("Member.R")
source("Library.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
lib <- Library$new()
for (line in input) {
  for (reply in lib$handle(line)) cat(reply, "\n", sep = "")
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online R compiler