Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
There are four exercises for this chapter. The first involves changing one of the examples, some of whose code was shown in the chapter, and the others require the creation of new functions. All the exercises are very short—the first is easy, the second is straightforward, but the third and fourth are quite challenging!
Copy the archive_file_list directory to, say, my_archive_file_list. Then modify the archive_file_list/archive_file_list.go file: Remove all the code for supporting different ArchiveFileList() functions except for ArchiveFileListMap() which should be renamed ArchiveFileList(). Then add the capability of handling .tar.bz2 (tarballs compressed with bzip2) files. This involves deleting about 11 lines from main(), deleting four functions, importing an additional package, adding one entry to the FunctionForSuffix map, and adding a few lines to the TarFileList() function. A solution is given in archive_file_list_ans/archive_file_list.go.
Create nonrecursive versions of the recursive IsPalindrome() functions shown earlier in the chapter (229 and 232
). In the palindrome_ans/palindrome.go solution file the nonrecursive ASCII-only function is 10 lines long and is radically different in structure to the recursive version. On the other hand, the nonrecursive UTF-8 function is 14 lines long and is very similar to the recursive version—although it does require some care.
Create a CommonPrefix() function that takes a []string argument and returns a string with the common prefix (which might be an empty string) of all the strings passed in. A solution is given in common_prefix/common_prefix.go; the solution is 22 lines long and uses a [][]rune to hold the strings to ensure that when iterating we work in terms of whole characters even if the strings have non-ASCII characters. The solution builds up the result in a bytes.Buffer. Despite being very short, this function is by no means easy! (Some examples follow the next exercise.)
Create a CommonPathPrefix() function that takes a []string of paths and returns a string with the common prefix (which might be an empty string) of all the paths passed in—the prefix must consist of zero or more complete path components. A solution is given in common_prefix/common_prefix.go; the solution is 27 lines long and uses a [][]string to hold the paths and the filepath.Separator to identify the platform-specific path separator. The solution builds up the result in a []string and joins them together as a single path at the end using the filepath.Join() function. Despite being really short, this function is challenging! (Some examples follow.)