Lab 5

 

This lab will focus on abstract data types

Structures

We've been creating data structure constructors and selectors by hand a lot lately, such as

    "A student is a data structure with three elements, an id, a name and a list of grades.

(define (make-student id name grades) (list id name grades))

(define (student-id student) (car student))

(define (student-name student) (cadr student))
(define (student-grades student) (caddr student))"

As with most things in Scheme, we can ABSTRACT this process, so we don't have to type as much. We can't quite do this ourselves (as we must manipulate the Scheme syntax to create a new special form---this is one example of the "macro" capability of the Lisp family of languages discussed in the Paul Graham paper) but it has been done in the Intermediate Student language and the Pretty Big languages that we have been using.

define-struct takes two arguments, a structure name (a symbol), and a list of selector names (also symbols). It is a Special Form, and so the arguments do not need to be quoted (just like define). So instead of writing the 4 lines above, we could write ONE LINE:
	(define-struct student (id name grades))
;defines (make-student i n g), (student-id s), (student-name s) and (student-grades s)
This is a simple example of how lisp macros can take the drudgery out of programming by abstracting code construction itself.

Exercise 1: A peer-to-peer network (like GNUtella) consists of individual nodes that are connected to the rest of the network through one or more neighboring nodes. In a simplified model, each node has only one neighbor and a list of files that it can serve. Every node has a unique number representing its address.

(define-struct file (name contents))
(define-struct node (address files neighbor))

A P2P-Network is one of:
 - empty
 - (make-node number list-of-File P2P-Network)

A list-of-file is one of
 - empty
 - (cons File list-of-file)

A File is a structure: (make-file symbol string)

Develop the function P2P-search. The function consumes the name of file and a P2P-network, and returns the address of the first node that is discovered to have the file or false if the file does not exist anywhere within the network.

Exercise 2: A copyright enforcement group wants to collect the addresses of all nodes on a P2P-Network that are hosting a particular file. Develop the function P2P-search-all, which is like P2P-search except that it returns the list of addresses of all nodes having a copy of the file being searched for.

Excercise 3: Develop the function P2P-get. The function consumes the name of file, the address of a node, and a P2P-network and returns the contents of the file. Assume that both the node and file exist.