Added functions inspired by Peter Norvig's PAIP Chapter 13.