The goal of the following sequence of exercises is to develop several common utility functions for directory and file systems, using our third and most refined model. Even though these functions process Scheme-based representations of files and directories, they give us a good idea how such real-world programs work.
Exercise 16.3.1
Translate the file system in figure
into a Scheme
representation. Remember to use empty for the content of the
files. Solution
To make the exercise more realistic, DrScheme supports the teachpack dir.ss. It introduces the two necessary structure definitions and a function to create representations of directories according to our third model:
;; create-dir : string -> dir ;; to create a representation of the directory that a-path specifies: ;; 1. Windows: (create-dir ``c:\\windows'') ;; 2. Mac: (create-dir ``My Disk:'') ;; 3. Unix: (create-dir ``/home/scheme/'') (define (create-dir a-path) ...)Use the function to create some small and large examples based on the directories in a real computer. Warning: For large directory trees, DrScheme may need a lot of time to build a representation. Use create-dir on small directory trees first.
Exercise 16.3.2
Develop the function how-many, which consumes a dir (according to
model 3) and produces the number of files in the dir tree. Test the
function on the directories created in exercise
. Why are we
confident that the function produces correct results? Solution
Exercise 16.3.3
Develop the function du-dir. The function consumes a directory and computes the total size of all the files in the entire directory tree. This function approximates a true disk-usage meter in that it assumes that directories don't require storage.
Refine the function to compute approximate sizes for subdirectories. Let's assume that storing a file and a directory in the content field costs 1 storage unit. Solution
Exercise 16.3.4
Develop the function find?, which consumes a dir and a file name and determines whether or not a file with this name occurs in the directory tree.
Challenge: Develop the function find. It consumes a directory d and a file name f. If (find? d f) is true, it produces a path to the file; otherwise it produces false. A path is a list of directory names. The first one is that of the given directory; the last one is that of the subdirectory whose files list contains f. For example:
(find TS 'part3) ;; expected value: (list 'TS 'Text)
(find TS 'read!) ;; expected value: (list 'TS)assuming TS is defined to be the directory in figure
Which read! file in figure
should find
discover? Generalize the function to return a list of paths if the file name occurs
more than once. Each path should lead to a different occurrence, and there should
be a path for each occurrence. Solution