This eBook will be updated occasionally so please periodically check the leanpub.com web page for this book for updates.

This is the fifth edition released September 2019.

If you found a copy of this book on the web and find it of value then please consider buying a copy at leanpub.com/lovinglisp to support the author and fund work for future updates.

## Preface for the Fifth Edition of “Loving Common Lisp, or the Savvy Programmer’s Secret Weapon”

Notes on the fifth edition published September 2019:

• A complete application for processing text to generate data for Knowledge Graphs (targeting the open source Neo4J graph database and also support RDF semantic web/linked data)
• A library for accessing the state of the art spaCy natural language processing (NLP) library and also a state of the art deep learning model. These models are implemented in thin Python wrappers that use Python libraries like spaCy, PyTorch, and TensorFlow. These examples replace a simple hybrid Java and Common Lisp example in previous editions.

I have added text and explanations as appropriate throughout the book. I removed the CouchDB examples.

I have made large changes to how the code for this book is packaged. I have reorganized the example code on GitHub by providing the examples as multiple QuickLisp libraries or applications. I now do this with all of my Common Lisp code and it makes it easier to write smaller libraries that can be composed into larger applications. In my own workflow, I also like to use Makefile targets to build standalone applications that can be run on other computers without installing Lisp development environments. Please follow the directions at the end of the Preface for configuring Quicklisp for easy builds and use of the example software for this book.

## Preface

Why Common Lisp? Isn’t Common Lisp an old language? Do many people still use Common Lisp?

I believe that using Lisp languages like Common Lisp, Clojure, Racket, and Scheme are all secret weapons useful in agile software development. An interactive development process and live production updates feel like a breath of fresh air if you have development on heavy weight like Java Enterprise Edition (JEE).

Yes, Common Lisp is an old language but with age comes stability and extremely good compiler technology. There is also a little inconsistency between different Common Lisp systems in such things as handling threads but with a little up front knowledge you can choose which Common Lisp systems will support your requirements.

I spent time writing this book to help you, dear reader. I release this book under the Creative Commons “share and share alike, no modifications, no commercial reuse” license and set the minimum purchase price to $5.00 in order to reach the most readers. Under this license you can share a PDF version of this book with your friends and coworkers. If you found this book on the web (or it was given to you) and if it provides value to you then please consider doing one of the following to support my future writing efforts and also to support future updates to this book: I enjoy writing and your support helps me write new editions and updates for my books and to develop new book projects. Thank you! ### Book editions The (latest) fourth edition of this book was released in May 2017 and the major changes are: • Added an example application KGCreator that processes text data to automatically generate data for Knowledge Graphs. This example application supports the Neo4J graph database as well as semantic web/linked data systems. The fourth edition of this book was released in May 2017 and the major changes are: • Added a backpropagation neural network example • Added a deep learning example using the Java based Armed Bear Common Lisp with the popular DeepLearning4j library • Added a heuristic search example • Added two machine learning examples (K-Means clustering and SVM classification) using the CLML library • A few edits to the previous text The third edition was released in October 2014. The second edition was released in 2013. the major changes made in the 2014 edition are: • I reworked the chapter Common Lisp Basics. • I added material to the chapter on using QuickLisp. ### Acknowledgments I would like to thank Jans Aasman for contributing as technical editor for the fourth edition of this book. Jans is CEO of Franz.com which sells Allegro Common Lisp as well as tools for semantic web and linked data applications. I would like to thank the following people who made suggestions for improving previous editions of this book: Sam Steingold, Andrew Philpot, Kenny Tilton, Mathew Villeneuve, Eli Draluk, Erik Winkels, Adam Shimali, and Paolo Amoroso. I would like to also thank several people who pointed out typo errors in this book and for specific suggestions: Martin Lightheart, Tong-Kiat Tan, Rainer Joswig, Gerold Rupprecht, and David Cortesi. I would like to thanks the following Reddit /r/lisp readers who pointed put mistakes in the fifth edition of this book: arnulfslayer, rpiirp, and itmuckel. I would like to thank Paul Graham for coining the phrase “The Secret Weapon” (in his excellent paper “Beating the Averages”) in discussing the advantages of Lisp. I would especially like to thank my wife Carol Watson for her fine work in editing this book. ### Setting Up Your Common Lisp Development System and Quicklisp These instructions assume the use of SBCL. See comments for LispWorks, Franz Common Lisp, and Closure Common List at the end of this section. I assume that you have installed SBCL and Quicklisp by following the instructions at lisp-lang.org/learn/getting-started. These instructions also guide you through installing the Slime extensions for Emacs. I use both Emacs + Slime and VSCode with Common Lisp plugins for editing Common Lisp. If you like VSCode then I recommend Yasuhiro Matsumoto’s Lisp plugin for syntax hilighting. For both Emacs and VSCode I usually run a separate REPL in a terminal window and don’t run an editor-integrated REPL. I think that am in the minority in using a separate REPL running in a shell. I have been using Common Lisp since about 1982 and Quicklisp has been the most revolutionary change in my Common Lisp development (even more so than getting a hardware Lisp Machine and the availability of Coral Common Lisp on the Macintosh). I am going to ask you, dear reader, to trust me and adopt the following advice that I have adopted from Zach Beane, the creator and maintainer of Quicklisp: • Create the file ~/.config/common-lisp/source-registry.conf.d/projects.conf if it does not exist on your system • Assuming that you have cloned the repository for this book (loving-common-lisp) in your home directory (if you have a special place where you clone git repos, adjust the following), edit this configuration file to look like this: This will make subdirectories of loving-common-lisp/src/ load-able by using Quicklisp. For example, the subdirectory loving-common-lisp/src/spacy_client contains a package named spacy that can now be accessed from any directory on your system using: $ sbcl (ql:quickload "spacy") * (spacy:spacy-client "My sister has a dog Henry. She loves him.") * (defvar x (spacy:spacy-client "President Bill Clinton went to Congress. He gave a speech on taxes and Mexico.")) * (spacy:spacy-data-entities x) * (spacy:spacy-data-tokens x) 

This example uses the deep learning NLP models in spaCy.

### List of Quicklisp Projects and Small Examples in this Book

The major example libraries and applications will be in their own packages. The function and data definitions for all short code snippets in this book are in a package loving-snippets in the subdirectory loving-common-lisp/src/loving_snippets. Whenever you work through the short examples in this book I will assume that you have opened a SBCL (or other Common Lisp) REPL and loaded this package:

 $sbcl * (ql:quickload "spacy_web_client")  On one of my Linux laptops, for reasons I haven’t discovered yet, using ~/.config/common-lisp/source-registry.conf.d/projects.conf to set a root directory for Quicklisp to look for packages does not work. If by small chance this does not work for you, you can set symbolic file links from the example book packages to your ~/quicklisp/local-projects directory. This is the directory where Quicklisp stores local copies of libraries that you install. For example: $ cd ~/quicklisp/local-projects $ln -s loving-common-lisp/src/loving_snippets .$ ln -s loving-common-lisp/src/kgcreator . $ln -s loving-common-lisp/src/kbnlp .  etc. Hopefully you won’t have to bother doing this workaround. While most of the longer examples in this book are Quicklisp projects, there are also many very short code snippets in the book that are found in the subdirectories src/code_snippets_for_book and a few short program examples not configured as Quicklisp projects in the src/loving_snippets subdirectory: The longer examples packaged as Quicklisp projects in the src directory are: • fasttag: my part of speech tagger • solr_examples: client for open source solr search engine • categorize_summarize: my NLP code for categorizing text and generating summaries • coref_web_client: client for a spaCy based web service that performs anaphora resolution (i.e., replaces pronouns in text with the nouns that the pronouns refer to) • hunchentoot_examples : examples so web services and web clients • spacy_web_client: client for a general purpose web service using state of the art deep learning models for NLP • clml_examples: examples using the Common List Machine Learning library • kbnlp: My NLP code • myutils: miscelanious functions that are used in several other example libraries in this book • webscrape: demo for how to scrape web sites • clsql_examples : examples showing how to access relational databases using the CLSQL library • entities_dbpedia : use the public DbPedia (data from WikiPedia) public web interface to get information about people, companies, locations, etc. • kgcreator: my application for processing text, extracting entities, and generating data for Knowledge Graphs (supports Neo4J and RDF semantic web/linked data applications • plotlib: a very simple plotting library that writes plots to PNG graphics files I have used the SBCL implementation of Common Lisp in this book. There are many fine Common Lisp implementations from Franz, LispWorks, Clozure Common Lisp, etc. If you have any great difficulty adopting the examples to your choice of Common Lisp implementations and performing web search does not suggest a solution then you can reach me through my web site markwatson.com. The examples that may not be portable are creating a standalone executable for my KGCreator example and the examples using the Common Lisp Machine Learning library. ## Introduction This book is intended to get you, the reader, programming quickly in Common Lisp. Although the Lisp programming language is often associated with artificial intelligence, this introduction is on general Common Lisp programming techniques. Later we will look at general example applications and artificial intelligence examples. The Common Lisp program examples are distributed on the github repo for this book. ### Why Did I Write this Book? Why the title “Loving Common Lisp”? Simple! I have been using Lisp for over 30 years and seldom do I find a better match between a programming language and the programming job at hand. I am not a total fanatic on Lisp, however. I often use Python for deep learning. I like both Ruby, Java and Javascript for server side programming, and the few years that I spent working on Nintendo video games and virtual reality systems for SAIC and Disney, I found C++ to be a good bet because of stringent runtime performance requirements. For some jobs, I find the logic-programming paradigm useful: I also enjoy the Prolog language. In any case, I love programming in Lisp, especially the industry standard Common Lisp. As I wrote the second edition of this book, I had been using Common Lisp almost exclusively for an artificial intelligence project for a health care company and for commercial product development. While working on the third edition of this book, I was not using Common Lisp professionally but since the release of the Quicklisp Common Lisp package manager I have found myself enjoying using Common Lisp more for small side projects. I use Quicklisp throughout in the third edition example code so you can easily install required libraries. For the fourth and fifth editions of this book I have added more examples using neural networks and deep learning. As programmers, we all (hopefully) enjoy applying our experience and brains for tackling interesting problems. My wife and I recently watched a two-night 7-hour PBS special “Joseph Campbell, and the Power of Myths.” Campbell, a college professor for almost 40 years, said that he always advised his students to “follow their bliss” and not to settle for jobs and avocations that are not what they truly want to do. That said I always feel that when a job calls for using Java, Python or other languages besides Lisp, that even though I may get a lot of pleasure from the job I am not following my bliss. My goal in this book is to introduce you to one of my favorite programming languages, Common Lisp. I assume that you already know how to program in another language but if you are a complete beginner you can still master the material in this book with some effort. I challenge you to make this effort. ### Free Software Tools for Common Lisp Programming There are several Common Lisp compilers and runtime tools available for free on the web: • CLISP – licensed under the GNU GPL and is available for Windows, Macintosh, and Linux/Unix • Clozure Common Lisp – open source with good Mac OS X and Linux support • CMU Common Lisp – open source implementation • SBCL – derived from CMU Common Lisp • ECL – compiles using a separate C/C++ compiler • ABCL – Armed Bear Common Lisp for the JVM I currently use SBCL. There are also fine commercial Common Lisp products: • LispWorks – high quality and reasonably priced system for Windows and Linux. No charge for distributing compiled applications lispworks.com • Allegro Common Lisp - high quality, great support and higher cost. franz.com • MCL – Macintosh Common Lisp. I used this Lisp environment in the late 1980s. MCL was so good that I gave away my Xerox 1108 Lisp Machine and switched to a Mac and MCL for my development work. Now open source but only runs on the old MacOS For working through this book, I will assume that you are using SBCL. ### How is Lisp Different from Languages like Java and C++? This is a trick question! Lisp is slightly more similar to Java than C++ because of automated memory management so we will start by comparing Lisp and Java. In Java, variables are strongly typed while in Common Lisp values are strongly typed. For example, consider the Java code: Here, in Java, variables are strongly typed so a variable x of type Float can’t legally be assigned a string value: the code in line 5 would generate a compilation error. Java and Lisp both provide automatic memory management. In either language, you can create new data structures and not worry about freeing memory when the data is no longer used, or to be more precise, is no longer referenced. Common Lisp is an ANSI standard language. Portability between different Common Lisp implementations and on different platforms is very good. I use Clozure Common Lisp, SBCL, Allegro Lisp (from Franz Inc), LispWorks, and Clisp that all run well on Windows,Mac OS X, and Linux. As a Common Lisp developer you will have great flexibility in tools and platforms. ANSI Common Lisp was the first object oriented language to become an ANSI standard language. The Common Lisp Object System (CLOS) is probably the best platform for object oriented programming. In C++ programs, a common bug that affects a program’s efficiency is forgetting to free memory that is no longer used. In a virtual memory system, the effect of a program’s increasing memory usage is usually just poorer system performance but can lead to system crashes or failures if all available virtual memory is exhausted. A worse type of C++ error is to free memory and then try to use it. Can you say “program crash”? C programs suffer from the same types of memory related errors. Since computer processing power is usually much less expensive than the costs of software development, it is almost always worth while to give up a few percent of runtime efficiency and let the programming environment of runtime libraries manage memory for you. Languages like Lisp, Ruby, Python, and Java are said to perform automatic garbage collection. I have written six books on Java, and I have been quoted as saying that for me, programming in Java is about twice as efficient (in terms of my time) as programming in C++. I base this statement on approximately ten years of C++ experience on projects for SAIC, PacBell, Angel Studios, Nintendo, and Disney. I find Common Lisp and other Lisp languages like Clojure and Scheme to be about twice as efficient (again, in terms of my time) as Java. That is correct: I am claiming a four times increase in my programming productivity when using Common Lisp vs. C++. What do I mean by programming productivity? Simple: for a given job, how long does it take me to design, code, debug, and later maintain the software for a given task. ### Advantages of Working in a Lisp Environment We will soon see that Lisp is not just a language; it is also a programming environment and runtime environment. The beginning of this book introduces the basics of Lisp programming. In later chapters, we will develop interesting and non-trivial programs in Common Lisp that I argue would be more difficult to implement in other languages and programming environments. The big win in programming in a Lisp environment is that you can set up an environment and interactively write new code and test new code in small pieces. We will cover programming with large amounts of data in the Chapter on Natural Language Processing, but let me share a use this general case for work that I do that is far more efficient in Lisp: Much of my Lisp programming used to be writing commercial natural language processing (NLP) programs for my company www.knowledgebooks.com. My Lisp NLP code uses a huge amount of memory resident data; for example: hash tables for different types of words, hash tables for text categorization, 200,000 proper nouns for place names (cities, counties, rivers, etc.), and about 40,000 common first and last names of various nationalities. If I was writing my NLP products in C++, I would probably use a relational database to store this data because if I read all of this data into memory for each test run of a C++ program, I would wait 30 seconds every time that I ran a program test. When I start working in any Common Lisp environment, I do have to load the linguistic data into memory one time, but then can code/test/code/test… for hours with no startup overhead for reloading the data that my programs need to run. Because of the interactive nature of Lisp development, I can test small bits of code when tracking down errors in the code. It is a personal preference, but I find the combination of the stable Common Lisp language and an iterative Lisp programming environment to be much more productive than, for example, the best Java IDEs (e.g., IntelliJ Idea is my favorite) and Microsoft’s VisualStudio.Net. ## Common Lisp Basics The material in this chapter will serve as an introduction to Common Lisp. I have attempted to make this book a self contained resource for learning Common Lisp and to provide code examples to perform common tasks. If you already know Common Lisp and bought this book for the code examples then you can probably skip this chapter. For working through this chapter we will be using the interactive shell, or repl, built into SBCL and other Common Lisp systems. For this chapter it is sufficient for you to download and install SBCL. Please install SBCL right now, if you have not already done so. ### Getting Started with SBCL When we start SBCL, we see an introductory message and then an input prompt. We will start with a short tutorial, walking you through a session using SBCL repl (other Common LISP systems are very similar). A repl is an interactive console where you type expressions and see the results of evaluating these expressions. An expression can be a large block of code pasted into the repl, using the load function to load Lisp code into the repl, calling functions to test them, etc. Assuming that SBCL is installed on your system, start SBCL by running the SBCL program: We started by defining a new variable x in line 11. Notice how the value of the defvar macro is the symbol that is defined. The Lisp reader prints X capitalized because symbols are made upper case (we will look at the exception later). In Lisp, a variable can reference any data type. We start by assigning a floating point value to the variable x, using the + function to add 1 to x in line 17, using the setq function to change the value of x in lines 23 and 29 first to another floating point value and finally setting x to a string value. One thing that you will have noticed: function names always occur first, then the arguments to a function. Also, parenthesis is used to separate expressions. I learned to program Lisp in 1976 and my professor half-jokingly told us that Lisp was an acronym for “Lots-of Irritating Superfluous Parenthesis.” There may be some truth in this when you are just starting with Lisp programming, but you will quickly get used to the parenthesis, especially if you use an editor like Emacs that automatically indents Lisp code for you and highlights the opening parenthesis for every closing parenthesis that you type. Many other editors also support coding in Lisp but I personally use Emacs or VScode (with Common Lisp plugins) to edit Lisp code. Before you proceed to the next chapter, please take the time to install SBCL on your computer and try typing some expressions into the Lisp listener. If you get errors, or want to quit, try using the quit function: As we discussed in the introduction, there are many different Lisp programming environments that you can choose from. I recommend a free set of tools: Emacs, slime, and SBCL. Emacs is a fine text editor that is extensible to work well with many programming languages and document types (e.g., HTML and XML). Slime is a Emacs extension package that greatly facilitates Lisp development. SBCL is a robust Common Lisp compiler and runtime system. We will cover the Quicklisp package manager and using Quicklisp to setup Slime and Emacs in a later chapter. I will not spend much time covering the use of Emacs as a text editor in this book since you can try most of the example code snippets in the book text by copying and then pasting them into a SBCL repl and by loading the book example source files directly into a repl. If you already use Emacs then I recommend that you do set up Slime sooner rather than later and start using it for development. If you are not already an Emacs user and do not mind spending the effort to learn Emacs, then search the web first for an Emacs tutorial. That said, you will easily be able to use the example code from this book using any text editor you like with a SBCL repl. I don’t use the vi or vim editors but if vi is your weapon of choice for editing text then a web search for “common lisp vi vim repl” should get you going for developing Common Lisp code with vi or vim. Here, we will assume that under Windows, Unix, Linux, or Mac OS X you will use one command window to run SBCL and a separate editor that can edit plain text files. ### Making the repl Nicer using rlwrap While reading the last section you (hopefully!) played with the SBCL interactive repl. If you haven’t played with the repl, I won’t get too judgmental except to say that if you do not play with the examples as you read you will not get the full benefit from this book. Did you notice that the backspace key does not work in the SBCL repl? The way to fix this is to install the GNU rlwrap utility. On OS X, assuming that you have homebrew installed, install rlwrap with: If you are running Ubuntu Linux, install rlwrap using: You can then create an alias for bash or zsh using something like the following to define a command rsbcl: This is fine, just remember to run sbcl if you don’t need rlwrap command line editing or run rsbcl when you do need command line editing. That said, I find that I always want to run SBCL with command line editing, so I redefine sbcl on my computers using: This alias is different on my laptops and servers, since I don’t usually install SBCL in the default installation directory. For each of my computers, I add an appropriate alias in my .zshrc file (if I am running zsh) or my .bashrc file (if I am running bash). ### The Basics of Lisp Programming Although we will use SBCL in this book, any Common Lisp environment will do fine. In previous sections, we saw the top-level Lisp prompt and how we could type any expression that would be evaluated: Notice that when we defined the function my-add-one in lines 7 and 8, we split the definition over two lines and on line 8 you don’t see the “*” prompt from SBCL – this lets you know that you have not yet entered a complete expression. The top level Lisp evaluator counts parentheses and considers a form to be complete when the number of closing parentheses equals the number of opening parentheses and an expression is complete when the parentheses match. I tend to count in my head, adding one for every opening parentheses and subtracting one for every closing parentheses – when I get back down to zero then the expression is complete. When we evaluate a number (or a variable), there are no parentheses, so evaluation proceeds when we hit a new line (or carriage return). The Lisp reader by default tries to evaluate any form that you enter. There is a reader macro that prevents the evaluation of an expression. You can either use the character or quote: Lisp supports both global and local variables. Global variables can be declared using defvar: One thing to be careful of when defining global variables with defvar: the declared global variable is dynamically scoped. We will discuss dynamic versus lexical scoping later, but for now a warning: if you define a global variable avoid redefining the same variable name inside functions. Lisp programmers usually use a global variable naming convention of beginning and ending dynamically scoped global variables with the * character. If you follow this naming convention and also do not use the * character in local variable names, you will stay out of trouble. For convenience, I do not always follow this convention in short examples in this book. Lisp variables have no type. Rather, values assigned to variables have a type. In this last example, the variable x was set to a string, then to a floating-point number. Lisp types support inheritance and can be thought of as a hierarchical tree with the type t at the top. (Actually, the type hierarchy is a DAG, but we can ignore that for now.) Common Lisp also has powerful object oriented programming facilities in the Common Lisp Object System (CLOS) that we will discuss in a later chapter. Here is a partial list of types (note that indentation denotes being a subtype of the preceding type): We can use the typep function to test the type of value of any variable or expression: A useful feature of all ANSI standard Common Lisp implementations’ top-level listener is that it sets * to the value of the last expression evaluated. For example: All Common Lisp environments set * to the value of the last expression evaluated. This example may be slightly confusing because * is also the prompt character in the SBCL repl that indicates that you can enter a new expression for evaluation. For example in line 3, the first * character is the repl prompt and the second * we type in to see that value of the previous expression that we typed into the repl. Frequently, when you are interactively testing new code, you will call a function that you just wrote with test arguments; it is useful to save intermediate results for later testing. It is the ability to create complex data structures and then experiment with code that uses or changes these data structures that makes Lisp programming environments so effective. Common Lisp is a lexically scoped language that means that variable declarations and function definitions can be nested and that the same variable names can be used in nested let forms; when a variable is used, the current let form is searched for a definition of that variable and if it is not found, then the next outer let form is searched. Of course, this search for the correct declaration of a variable is done at compile time so there need not be extra runtime overhead. We can nest defun special form inside each other and inside let expressions. We can also use the special forms flet and labels to define functions inside a scoped environment. Functions defined inside a labels special form can be recursive while functions defined inside a flet special form can not be recursive. Consider the following example in the file nested.lisp (all example files are in the src directory): We define a top level flet special form in lines 1-5 that defines two nested functions add-one and add-two and then calls each nested function in the body of the flet special form. For many years I have used nested defun special forms inside let expressions for defining local functions and you will notice this use in a few later examples. However, functions defined inside defun special forms have global visibility so they are not hidden in the local context where they are defined. The example of a nested defun in lines 7-12 shows that the function test2 has global visibility inside the current package. Functions defined inside of a flet special form have access to variables defined in the outer scope containing the flet (also applies to labels). We see this in lines 14-24 where the local variables x and y defined in the let expression are visible inside the function nested-function defined inside the flet. The final example in lines 26-31 shows a recursive function defined inside a labels special form. Assuming that we started SBCL in the src directory we can then use the Lisp load function to evaluate the contents of the file nested.lisp using the load function: The function load returned a value of t (prints in upper case as T) after successfully loading the file. We will use Common Lisp vectors and arrays frequently in later chapters, but will also briefly introduce them here. A singly dimensioned array is also called a vector. Although there are often more efficient functions for handling vectors, we will just look at generic functions that handle any type of array, including vectors. Common Lisp provides support for functions with the same name that take different argument types; we will discuss this in some detail when we cover this in the later chapter on CLOS. We will start by defining three vectors v1, v2, and v3: In line 1, we are defining a one-dimensional array, or vector, with three elements. In line 3 we specify the default value assigned to each element of the array v2. In line 5 I use the form for specifying array literals using the special character #. The function aref can be used to access any element in an array: Notice how indexing of arrays is zero-based; that is, indices start at zero for the first element of a sequence. Also notice that array elements can be any Lisp data type. So far, we have used the special operator setq to set the value of a variable. Common Lisp has a generalized version of setq called setf that can set any value in a list, array, hash table, etc. You can use setf instead of setq in all cases, but not vice-versa. Here is a simple example: When writing new code or doing quick programming experiments, it is often easiest (i.e., quickest to program) to use lists to build interesting data structures. However, as programs mature, it is common to modify them to use more efficient (at runtime) data structures like arrays and hash tables. ### Symbols We will discuss symbols in more detail the Chapter on Common Lisp Packages. For now, it is enough for you to understand that symbols can be names that refer to variables. For example: Note that the first defvar returns the defined symbol as its value. Symbols are almost always converted to upper case. An exception to this “upper case rule” is when we define symbols that may contain white space using vertical bar characters: ### Operations on Lists Lists are a fundamental data structure of Common Lisp. In this section, we will look at some of the more commonly used functions that operate on lists. All of the functions described in this section have something in common: they do not modify their arguments. In Lisp, a cons cell is a data structure containing two pointers. Usually, the first pointer in a cons cell will point to the first element in a list and the second pointer will point to another cons representing the start of the rest of the original list. The function cons takes two arguments that it stores in the two pointers of a new cons data structure. For example: The first form evaluates to a cons data structure while the second evaluates to a cons data structure that is also a proper list. The difference is that in the second case the second pointer of the freshly created cons data structure points to another cons cell. First, we will declare two global variables l1 and l2 that we will use in our examples. The list l1 contains five elements and the list l2 contains four elements: You can also use the function list to create a new list; the arguments passed to function list are the elements of the created list: The function car returns the first element of a list and the function cdr returns a list with its first element removed (but does not modify its argument): Using combinations of car and cdr calls can be used to extract any element of a list: Notice that we can combine calls to car and cdr into a single function call, in this case the function cadr. Common Lisp defines all functions of the form cXXr, cXXXr, and cXXXXr where X can be either a or d. Suppose that we want to extract the value 5 from the nested list l1. Some experimentation with using combinations of car and cdr gets the job done: The function last returns the last cdr of a list (i.e., the last element, in a list): Common list supplies alternative functions to car and cdr that you might find more readable: first, second, third, fourth, and rest. Here are some examples: The function nth takes two arguments: an index of a top-level list element and a list. The first index argument is zero based: The function cons adds an element to the beginning of a list and returns as its value a new list (it does not modify its arguments). An element added to the beginning of a list can be any Lisp data type, including another list: The function append takes two lists as arguments and returns as its value the two lists appended together: A frequent error that beginning Lisp programmers make is not understanding shared structures in lists. Consider the following example where we generate a list y by reusing three copies of the list x: When we change the shared structure referenced by the variable x that change is reflected three times in the list y. When we create the list stored in the variable z we are not using a shared structure. ### Using Arrays and Vectors Using lists is easy but the time spent accessing a list element is proportional to the length of the list. Arrays and vectors are more efficient at runtime than long lists because list elements are kept on a linked-list that must be searched. Accessing any element of a short list is fast, but for sequences with thousands of elements, it is faster to use vectors and arrays. By default, elements of arrays and vectors can be any Lisp data type. There are options when creating arrays to tell the Common Lisp compiler that a given array or vector will only contain a single data type (e.g., floating point numbers) but we will not use these options in this book. Vectors are a specialization of arrays; vectors are arrays that only have one dimension. For efficiency, there are functions that only operate on vectors, but since array functions also work on vectors, we will concentrate on arrays. In the next section, we will look at character strings that are a specialization of vectors. We could use the generalized make-sequence function to make a singularly dimensioned array (i.e., a vector). Restart sbcl and try: In this example, notice the print format for vectors that looks like a list with a proceeding # character. As seen in the last section, we use the function make-array to create arrays: Notice the print format of an array: it looks like a list proceeded by a # character and the integer number of dimensions. Instead of using make-sequence to create vectors, we can pass an integer as the first argument of make-array instead of a list of dimension values. We can also create a vector by using the function vector and providing the vector contents as arguments: The function aref is used to access sequence elements. The first argument is an array and the remaining argument(s) are array indices. For example: ### Using Strings It is likely that even your first Lisp programs will involve the use of character strings. In this section, we will cover the basics: creating strings, concatenating strings to create new strings, for substrings in a string, and extracting substrings from longer strings. The string functions that we will look at here do not modify their arguments; rather, they return new strings as values. For efficiency, Common Lisp does include destructive string functions that do modify their arguments but we will not discuss these destructive functions here. We saw earlier that a string is a type of vector, which in turn is a type of array (which in turn is a type of sequence). A full coverage of the Common Lisp type system is outside the scope of this tutorial introduction to Common Lisp; a very good treatment of Common Lisp types is in Guy Steele’s “Common Lisp, The Language” which is available both in print and for free on the web. Many of the built in functions for handling strings are actually more general because they are defined for the type sequence. The Common Lisp Hyperspec is another great free resource that you can find on the web. I suggest that you download an HTML version of Guy Steele’s excellent reference book and the Common Lisp Hyperspec and keep both on your computer. If you continue using Common Lisp, eventually you will want to read all of Steele’s book and use the Hyperspec for reference. The following text was captured from input and output from a Common Lisp repl. First, we will declare two global variables s1 and space that contain string values: One of the most common operations on strings is to concatenate two or more strings into a new string: Notice that the first argument of the function concatenate is the type of the sequence that the function should return; in this case, we want a string. Another common string operation is search for a substring: If the search string (first argument to function search) is not found, function search returns nil, otherwise search returns an index into the second argument string. Function search takes several optional keyword arguments (see the next chapter for a discussion of keyword arguments): For our discussion, we will just use the keyword argument :start2 for specifying the starting search index in the second argument string and the :from-end flag to specify that search should start at the end of the second argument string and proceed backwards to the beginning of the string: The sequence function subseq can be used for strings to extract a substring from a longer string: Here, the second argument specifies the starting index; the substring from the starting index to the end of the string is returned. An optional third index argument specifies one greater than the last character index that you want to extract: It is frequently useful to remove white space (or other) characters from the beginning or end of a string: The character #\space is the space character. Other common characters that are trimmed are #\tab and #\newline. There are also utility functions for making strings upper or lower case: We have not yet discussed equality of variables. The function eq returns true if two variables refer to the same data in memory. The function eql returns true if the arguments refer to the same data in memory or if they are equal numbers or characters. The function equal is more lenient: it returns true if two variables print the same when evaluated. More formally, function equal returns true if the car and cdr recursively equal to each other. An example will make this clearer: For strings, the function string= is slightly more efficient than using the function equal: Common Lisp strings are sequences of characters. The function char is used to extract individual characters from a string: ### Using Hash Tables Hash tables are an extremely useful data type. While it is true that you can get the same effect by using lists and the assoc function, hash tables are much more efficient than lists if the lists contain many elements. For example: The second argument to function assoc is a list of cons cells. Function assoc searches for a sub-list (in the second argument) that has its car (i.e., first element) equal to the first argument to function assoc. The perhaps surprising thing about this example is that assoc seems to work with an integer as the first argument but not with a string. The reason for this is that by default the test for equality is done with eql that tests two variables to see if they refer to the same memory location or if they are identical if they are numbers. In the last call to assoc we used “:test #’equal” to make assoc use the function equal to test for equality. The problem with using lists and assoc is that they are very inefficient for large lists. We will see that it is no more difficult to code with hash tables. A hash table stores associations between key and value pairs, much like our last example using the assoc function. By default, hash tables use eql to test for equality when looking for a key match. We will duplicate the previous example using hash tables: Notice that gethash returns multiple values: the first value is the value matching the key passed as the first argument to function gethash and the second returned value is true if the key was found and nil otherwise. The second returned value could be useful if hash values are nil. Since we have not yet seen how to handle multiple returned values from a function, we will digress and do so here (there are many ways to handle multiple return values and we are just covering one of them): Assuming that variables a and b are already declared, the variable a will be set to the first returned value from gethash and the variable b will be set to the second returned value. If we use symbols as hash table keys, then using eql for testing for equality with hash table keys is fine: However, we saw that eql will not match keys with character string values. The function make-hash-table has optional key arguments and one of them will allow us to use strings as hash key values: Here, we are only interested in the first optional key argument :test that allows us to use the function equal to test for equality when matching hash table keys. For example: It is often useful to be able to enumerate all the key and value pairs in a hash table. Here is a simple example of doing this by first defining a function my-print that takes two arguments, a key and a value. We can then use the maphash function to call our new function my-print with every key and value pair in a hash table: The function my-print is applied to each key/value pair in the hash table. There are a few other useful hash table functions that we demonstrate here: The function hash-table-count returns the number of key and value pairs in a hash table. The function remhash can be used to remove a single key and value pair from a hash table. The function clrhash clears out a hash table by removing all key and value pairs in a hash table. It is interesting to note that clrhash and remhash are the first Common Lisp functions that we have seen so far that modify any of its arguments, except for setq and setf that are macros and not functions. ### Using Eval to Evaluate Lisp Forms We have seen how we can type arbitrary Lisp expressions in the Lisp repl listener and then they are evaluated. We will see in the Chapter on Input and Output that the Lisp function read evaluates lists (or forms) and indeed the Lisp repl uses function read. In this section, we will use the function eval to evaluate arbitrary Lisp expressions inside a program. As a simple example: Using the function eval, we can build lists containing Lisp code and evaluate generated code inside our own programs. We get the effect of “data is code”. A classic Lisp program, the OPS5 expert system tool, stored snippets of Lisp code in a network data structure and used the function eval to execute Lisp code stored in the network. A warning: the use of eval is likely to be inefficient in non-compiled code. For efficiency, the OPS5 program contained its own version of eval that only interpreted a subset of Lisp used in the network. ### Using a Text Editor to Edit Lisp Source Files I usually use Emacs, but we will briefly discuss the editor vi also. If you use vi (e.g., enter “vi nested.lisp”) the first thing that you should do is to configure vi to indicate matching opening parentheses whenever a closing parentheses is typed; you do this by typing “:set sm” after vi is running. If you choose to learn Emacs, enter the following in your .emacs file (or your _emacs file in your home directory if you are running Windows): Now, whenever you open a file with the extension of “lisp”, “lsp”, or “cl” (for “Common Lisp”) then Emacs will automatically use a Lisp editing mode. I recommend searching the web using keywords “Emacs tutorial” to learn how to use the basic Emacs editing commands - we will not repeat this information here. I do my professional Lisp programming using free software tools: Emacs, SBCL, Clozure Common Lisp, and Clojure. I will show you how to configure Emacs and Slime in the last section of the Chapter on Quicklisp. ### Recovering from Errors When you enter forms (or expressions) in a Lisp repl listener, you will occasionally make a mistake and an error will be thrown. Here is an example where I am not showing all of the output when entering help when an error is thrown: Here, I first used the backtrace command :bt to print the sequence of function calls that caused the error. If it is obvious where the error is in the code that I am working on then I do not bother using the backtrace command. I then used the abort command :a to recover back to the top level Lisp listener (i.e., back to the greater than prompt). Sometimes, you must type :a more than once to fully recover to the top level greater than prompt. ### Garbage Collection Like other languages like Java and Python, Common Lisp provides garbage collection (GC) or automatic memory management. In simple terms, GC occurs to free memory in a Lisp environment that is no longer accessible by any global variable (or function closure, which we will cover in the next chapter). If a global variable *variable-1* is first set to a list and then if we later then set *variable-1* to, for example nil, and if the data referenced in the original list is not referenced by any other accessible data, then this now unused data is subject to GC. In practice, memory for Lisp data is allocated in time ordered batches and ephemeral or generational garbage collectors garbage collect recent memory allocations far more often than memory that has been allocated for a longer period of time. ### Loading your Working Environment Quickly When you start using Common Lisp for large projects, you will likely have many files to load into your Lisp environment when you start working. Most Common Lisp implementations have a function called defsystem that works somewhat like the Unix make utility. While I strongly recommend defsystem for large multi-person projects, I usually use a simpler scheme when working on my own: I place a file loadit.lisp in the top directory of each project that I work on. For any project, its loadit.lisp file loads all source files and initializes any global data for the project. Another good technique is to create a Lisp image containing all the code and data for all your projects. There is an example of this in the first section of the Chapter on NLP. In this example, it takes a few minutes to load the code and data for my NLP (natural language processing) library so when I am working with it I like to be able to quickly load a SBCL Lisp image. All Common Lisp implementations have a mechanism for dumping a working image containing code and data. ### Functional Programming Concepts There are two main styles for doing Common Lisp development. Object oriented programming is well supported (see the Chapter on CLOS) as is functional programming. In a nut shell, functional programming means that we should write functions with no side effects. First let me give you a non-functional example with side effects: This example using CLOS is non-functional because we modify the value of an argument to the function. Some functional languages like the Lisp Clojure language and the Haskell language dissuade you from modifying arguments to functions. With Common Lisp you should make a decision on which approach you like to use. Functional programming means that we avoid maintaining state inside of functions and treat data as immutable (i.e., once an object is created, it is never modified). We could modify the last example to be function by creating a new car object inside the function, copy the attributes of the car passed as an object, change the color to “red” of the new car object, and return the new car instance as the value of the function. Functional programming prevents many types of programming errors, makes unit testing simpler, and makes programming for modern multi-core CPUs easier because read-only objects are inherently thread safe. Modern best practices for the Java language also prefer immutable data objects and a functional approach. ## Defining Lisp Functions In the previous chapter, we defined a few simple functions. In this chapter, we will discuss how to write functions that take a variable number of arguments, optional arguments, and keyword arguments. The special form defun is used to define new functions either in Lisp source files or at the top level Lisp listener prompt. Usually, it is most convenient to place function definitions in a source file and use the function load to load them into our Lisp working environment. In general, it is bad form to use global variables inside Lisp functions. Rather, we prefer to pass all required data into a function via its argument list and to get the results of the function as the value (or values) returned from a function. Note that if we do require global variables, it is customary to name them with beginning and ending * characters; for example: Then in this example, if you see the variable *lexical-hash-table* inside a function definition, you will know that at least by naming convention, that this is a global variable. In Chapter 1, we saw an example of using lexically scoped local variables inside a function definition (in the example file nested.lisp). There are several options for defining the arguments that a function can take. The fastest way to introduce the various options is with a few examples. First, we can use the &aux keyword to declare local variables for use in a function definition: It is considered better coding style to use the let special operator for defining auxiliary local variables; for example: You will probably not use &aux very often, but there are two other options for specifying function arguments: &optional and &key. The following code example shows how to use optional function arguments. Note that optional arguments must occur after required arguments. In this example, the optional argument b was not given a default value so if unspecified it will default to nil. The optional argument c is given a default value of 123. We have already seen the use of keyword arguments in built-in Lisp functions. Here is an example of how to specify key word arguments in your functions: ### Using Lambda Forms It is often useful to define unnamed functions. We can define an unnamed function using lambda; for example, let’s look at the example file src/lambda1.lisp. But first, we will introduce the Common Lisp function funcall that takes one or more arguments; the first argument is a function and any remaining arguments are passed to the function bound to the first argument. For example: In the first two calls to funcall here, we simply quote the function name that we want to call. In the third example, we use a better notation by quoting with #’. We use the #’ characters to quote a function name. Here is the example file src/lambda1.lisp: Here, we define a function using lambda and set the value of the local variable my-func to the unnamed function’s value. Here is output from the function test: The ability to use functions as data is surprisingly useful. For now, we will look at a simple example: Notice that the second call to function testfn prints “100” twice: the first time as a side effect of calling the function print and the second time as the returned value of testfn (the function print returns what it is printing as its value). ### Using Recursion Later, we will see how to use special Common Lisp macros for programming repetitive loops. In this section, we will use recursion for both coding simple loops and as an effective way to solve a variety of problems that can be expressed naturally using recursion. As usual, the example programs for this section are found in the src directory. In the file src/recursion1.lisp, we see our first example of recursion: This example is simple, but it is useful for discussing a few points. First, notice how the function recursion1 calls itself with an argument value of one greater than its own input argument only if the input argument “value” is less than 5. This test keeps the function from getting in an infinite loop. Here is some sample output: Why did the call on line 24 not loop via recursion? Because the input argument is not less than 5, no recursion occurs. ### Closures We have seen that functions can take other functions as arguments and return new functions as values. A function that references an outer lexically scoped variable is called a closure. The example file src/closure1.lisp contains a simple example: Here the function fortune is defined inside a let form. Because the local variable fortunes is referenced inside the function fortune, the variable fortunes exists after the let form is evaluated. It is important to understand that usually a local variable defined inside a let form “goes out of scope” and can no longer be referenced after the let form is evaluated. However, in this example, there is no way to access the contents of the variable fortunes except by calling the function fortune. At a minimum, closures are a great way to hide variables. Here is some output from loading the src/closure1.lisp file and calling the function fortune several times: ## Quicklisp For several decades managing packages and libraries was a manual process when developing Lisp systems. I used to package the source code for specific versions of libraries as part of my Common Lisp projects. Early package management systems mk-defsystem and ASDF were very useful, but I did not totally give up my practice keeping third party library source code with my projects until Zach Beane created the Quicklisp package system. You will need to have Quicklisp installed for many of the examples later in this book so please take the time to install it now as per the instructions on the Quicklisp web site. ### Using Quicklisp to Find Packages We will need the Common Lisp Hunchentoot library later in the Chapter on Network Programming so we will install it now using Quicklisp. We already know the package name we want, but let’s start by using Quicklisp to search for all packages with “hunchentoot” in the package name: We want the base package seen in line 3 and we can install the base package as seen in the following example: In line 1, I refer to the package name using a symbol :hunchentoot but using the string “hunchentoot” would have worked the same. The first time you ql:quickload a library you may see additional printout. In most of the rest of this book, when I install or use a package by calling the ql:quickload function I do not show the output from this function when in the repl listings. Now, we can use the fantastically useful Common Lisp function apropos to see what was just installed: As long as you are thinking about the new tool Quicklisp that is now in your tool chest, you should install the rest of the packages and libraries that you will need for working through the rest of this book. I will show the statements needed to load more libraries without showing the output printed in the repl as each package is loaded: You need to have the Postgres and MySQL client developer libraries installed on your system for the clsql-postgresql and clsql-mysql installations to work. ### Using Quicklisp to Configure Emacs and Slime I assume that you have Emacs installed on your system. In a repl you can setup the Slime package that allows Emacs to connect to a running Lisp environment: Pay attention to the output in the repl. On my system the output contained the following: If you installed rlwrap and defined an alias for running SBCL, make sure you set the inferior lisp program to the absolute path of the SBCL executable; on my system I set the following in my .emacs file: I am not going to cover using Emacs and Slime: there are many good tutorials on the web you can read. In later chapters we will write libraries and applications as Quicklisp projects so that you will be able to load your own libraries, making it easier to write small libraries that you can compose into larger applications. ## Defining Common Lisp Macros We saw in the last chapter how the Lisp function eval could be used to evaluate arbitrary Lisp code stored in lists. Because eval is inefficient, a better way to generate Lisp code automatically is to define macro expressions that are expanded inline when they are used. In most Common Lisp systems, using eval requires the Lisp compiler to compile a form on-the-fly which is not very efficient. Some Lisp implementations use an interpreter for eval which is likely to be faster but might lead to obscure bugs if the interpreter and compiled code do not function identically. ### Example Macro The file src/macro1.lisp contains both a simple macro and a function that uses the macro. This macro example is a bit contrived since it could be just a function definition, but it does show the process of creating and using a macro. We are using the gensym function to define a new unique symbol to reference a temporary variable: The backquote character seen at the beginning of line 5 is used to quote a list in a special way: nothing in the list is evaluated during macro expansion unless it is immediately preceded by a comma character. In this case, we specify ,a-list because we want the value of the macro’s argument a-list to be substituted into the specially quoted list. We will look at dolist in some detail in the next chapter but for now it is sufficient to understand that dolist is used to iterate through the top-level elements of a list, for example: Returning to our macro example in the file src/macro1.lisp, we will try the function test that uses the macro double-list: ### Using the Splicing Operator Another similar example is in the file src/macro2.lisp: Here, the splicing operator ,@ is used to substitute in the list args in the macro double-args. ### Using macroexpand-1 The function macroexpand-1 is used to transform macros with arguments into new Lisp expressions. For example: Writing macros is an effective way to extend the Lisp language because you can control the code passed to the Common Lisp compiler. In both macro example files, when the function test was defined, the macro expansion is done before the compiler processes the code. We will see in the next chapter several useful macros included in Common Lisp. We have only “scratched the surface” looking at macros; the interested reader is encouraged to search the web using, for example, “Common Lisp macros.” ## Using Common Lisp Loop Macros In this chapter, we will discuss several useful macros for performing iteration (we saw how to use recursion for iteration in Chapter 2): • dolist – a simple way to process the elements of a list • dotimes – a simple way to iterate with an integer valued loop variable • do – the most general looping macro • loop – a complex looping macro that I almost never use in my own code because it does not look “Lisp like.” I don’t use the loop macro in this book. Many programmers do like the loop macro so you are likely to see it when reading other people’s code. ### dolist We saw a quick example of dolist in the last chapter. The arguments of the dolist macro are: Usually, the dolist macro returns nil as its value, but we can add a third optional argument which will be returned as the generated expression’s value; for example: The first argument to the dolist macro is a local lexically scoped variable. Once the code generated by the dolist macro finishes executing, this variable is undefined. ### dotimes The dotimes macro is used when you need a loop with an integer loop index. The arguments of the dotimes macro are: Usually, the dotimes macro returns nil as its value, but we can add a third optional argument that will be returned as the generated expression’s value; for example: As with the dolist macro, you will often use a let form inside a dotimes macro to declare additional temporary (lexical) variables. ### do The do macro is more general purpose than either dotimes or dolist but it is more complicated to use. Here is the general form for using the do looping macro: There is a similar macro do* that is analogous to let* in that loop variable values can depend on the values or previously declared loop variable values. As a simple example, here is a loop to print out the integers from 0 to 3. This example is in the file src/do1.lisp: ;; example do macro use In this example, we only declare one loop variable so we might as well as used the simpler dotimes macro. Here we load the file src/do1.lisp: You will notice that we do not see the return value of the do loop (i.e., the string “value-of-do-loop”) because the top-level form that we are evaluating is a call to the function load; we do see the return value of load printed. If we had manually typed this example loop in the Lisp listener, then you would see the final value value-of-do-loop printed. ### Using the loop Special Form to Iterate Over Vectors or Arrays We previousely used dolist to iterate over elements in lists. For efficiency we will often use vectors (one dimensional arrays) and we can use loop to similarly handle vectors: where testdata is a one dimensional array (a vector) and inside the do block the local variable td is assigned to each element in the vector. ## Common Lisp Package System In the simple examples that we have seen so far, all newly created Lisp symbols have been placed in the default package. You can always check the current package by evaluating the expression package: As we will use in the following example, the package :cl is an alias for :common-lisp-user. We will define a new package :my-new-package and two functions foo1 and foo2 inside the package. Externally to this package, assuming that it is loaded, we can access foo2 using my-new-package:foo2. foo1 is not exported so it can not be accessed this way. However, once again assuming this package is loaded, we can always start a symbol name with a package name and two colon characters if we want to use a symbol defined in another package so we can use my-new-package::foo1. When I leave package :my-new-package in line 22 and return to package :cl, and try to access my-new-package:foo1 notice that an error is thrown. On line 3 we define the alias :p1 for the packkage :my-new-package and we use this alias in line 44. Since we specified a nickname in the defpackage expression, Common Lisp uses the nickname (in this case P1 in calling function foo2 that is exported from package :my-new-package. Near the end of the last example, we switched back to the default package COMMON-LISP-USER so we had to specify the package name for the function foo2. When you are writing very large Common Lisp programs, it is useful to be able to break up the program into different modules and place each module and all its required data in different name spaces by creating new packages. Remember that all symbols, including variables, generated symbols, CLOS methods, functions, and macros are in some package. When I use a package I usually place everything in the package in a single source file. I put a defpackage expression at the top of the file immediately followed by an in-package expression to switch to the new package. Note that whenever a new file is loaded into a Lisp environment, the current package is set back to the default package COMMON-LISP-USER. Since the use of packages is a common source of problems for new users, you might want to “put off” using packages until your Common Lisp programs become large enough to make the use of packages effective. ## Input and Output We will see that the input and output of Lisp data is handled using streams. Streams are powerful abstractions that support common libraries of functions for writing to the terminal, to files, to sockets, and to strings. In all cases, if an input or output function is called without specifying a stream, the default for input stream is *standard-input* and the default for output stream is *standard-output*. These defaults streams are connected to the Lisp listener that we discussed in Chapter 2. ### The Lisp read and read-line Functions The function read is used to read one Lisp expression. Function read stops reading after reading one expression and ignores new line characters. We will look at a simple example of reading a file test.dat using the example Lisp program in the file read-test-1.lisp. Both of these files, as usual, can be found in the directory src that came bundled with this web book. Start your Lisp program in the src directory. The contents of the file test.dat is: In the function read-test-1, we use the macro with-open-file to read from a file. To write to a file (which we will do later), we can use the keyword arguments :direction :output. The first argument to the macro with-open-file is a symbol that is bound to a newly created input stream (or an output stream if we are writing a file); this symbol can then be used in calling any function that expects a stream argument. Notice that we call the function read with three arguments: an input stream, a flag to indicate if an error should be thrown if there is an I/O error (e.g., reaching the end of a file), and the third argument is the value that function read should return if the end of the file (or stream) is reached. When calling read with these three arguments, either the next expression from the file test.dat will be returned, or the value nil will be returned when the end of the file is reached. If we do reach the end of the file, the local variable x will be assigned the value nil and the function return will break out of the dotimes loop. One big advantage of using the macro with-open-file over using the open function (which we will not cover) is that the file stream is automatically closed when leaving the code generated by the with-open-file macro. The contents of file read-test-1.lisp is: Here is the output that you will see if you load the file read-test-1.lisp and execute the expression (read-test-1): Note: the string “the cat bit the rat” prints as a string (with quotes) because we used a ~S instead of a ~A in the format string in the call to function format. In this last example, we passed the file name as a string to the macro with-open-file. This is not generally portable across all operating systems. Instead, we could have created a pathname object and passed that instead. The pathname function can take eight different keyword arguments, but we will use only the two most common in the example in the file read-test-2.lisp in the src directory. The following listing shows just the differences between this example and the last: Here, we are specifying that we should look for the for the file test.dat in the subdirectory testdata. Note: I almost never use pathnames. Instead, I specify files using a string and the character / as a directory delimiter. I find this to be portable for the Macintosh, Windows, and Linux operating systems using all Common Lisp implementations. The file readline-test.lisp is identical to the file read-test-1.lisp except that we call function readline instead of the function read and we change the output format message to indicate that an entire line of text has been read When we execute the expression (readline-test), notice that the string contained in the second line of the input file has the quote characters escaped: We can also create an input stream from the contents of a string. The file read-from-string-test.lisp is very similar to the example file read-test-1.lisp except that we use the macro with-input-from-string (notice how I escaped the quote characters used inside the test string): We see the following output when we load the file read-from-string-test.lisp: We have seen how the stream abstraction is useful for allowing the same operations on a variety of stream data. In the next section, we will see that this generality also applies to the Lisp printing functions. ### Lisp Printing Functions All of the printing functions that we will look at in this section take an optional last argument that is an output stream. The exception is the format function that can take a stream value as its first argument (or t to indicate *standard-output*, or a nil value to indicate that format should return a string value). Here is an example of specifying the optional stream argument: The function print prints Lisp objects so that they can (usually) be read back using function read. The corresponding function princ is used to print for “human consumption”. For example: Both print and princ return their first argument as their return value, which you see in the previous output. Notice that princ also does not print a new line character, so princ is often used with terpri (which also takes an optional stream argument). We have also seen many examples in this web book of using the format function. Here is a different use of format, building a string by specifying the value nil for the first argument: We have not yet seen an example of writing to a file. Here, we will use the with-open-file macro with options to write a file and to delete any existing file with the same name: Here is the result of evaluating this expression (i.e., the contents of the newly created file test1.dat in the src directory): Notice that print generates a new line character before printing its argument. ## Plotting Data We will use Zach Beane’s vecto library for plotting data with the results written to files. Ideally we would like to have interactive plotting capability but for the purposes of this book I need to support the combinations of all Common Lisp implementations on multiple operating systems. Interactive plotting libraries are usually implementation and OS dependent. ### Implementing the Library The examples here are all contained in the directory src/plotlib and is packaged as a Quicklisp loadable library. This library will be used in later chapters. When I work on my macOS laptop, I leave the output graphics file open in the Preview App and whenever I rerun a program producing graphics in the REPL, making the preview App window active refreshes the graphics display. The following listing shows the file plotlib.lisp that is a simple wrapper for the vecto Common Lisp plotting library. Please note that I only implemented wrappers for vecto functionality that I need for later examples in this book, so the following code is not particularly general but should be easy enough for you to extend for the specific needs of your projects. This plot library is used in later examples in the chapters on search, backpropagation neural networks and Hopfield neural networks. I prefer using implementation and operating specific ploting libraires for generating interactive plots but the advantage of writing plot data to a file using the vecto library is that the code is portable across operating systems and Common Lisp implementations. ### Packaging as a Quicklisp Project The two files src/plotlib/plotlib.asd src/plotlib/package.lisp configure the library. The file package.lisp defines the required library vecto and lists the functions that are publicly exported from the library: To run the test function provided with this library you load the library and preface exported function names with the package name plotlib: as in this example: In addition to a package.lisp file we also use a file with the extension .asd If you have specified a dependency that is not already downloaded to your computer, Quicklisp will install the dependency for you. ## Common Lisp Object System - CLOS CLOS was the first ANSI standardized object oriented programming facility. While I do not use classes and objects as often in my Common Lisp programs as I do when using Java and Smalltalk, it is difficult to imagine a Common Lisp program of any size that did not define and use at least a few CLOS classes. The example program for this chapter in the file src/HTMLstream.lisp. I used this CLOS class about ten years ago in a demo for my commercial natural language processing product to automatically generate demo web pages. We are going to start our discussion of CLOS somewhat backwards by first looking at a short test function that uses the HTMLstream class. Once we see how to use this example CLOS class, we will introduce a small subset of CLOS by discussing in some detail the implementation of the HTMLstream class and finally, at the end of the chapter, see a few more CLOS programming techniques. This book only provides a brief introduction to CLOS; the interested reader is encouraged to do a web search for “CLOS tutorial”. The macros and functions defined to implement CLOS are a standard part of Common Lisp. Common Lisp supports generic functions, that is, different functions with the same name that are distinguished by different argument types. ### Example of Using a CLOS Class The file src/HTMLstream.lisp contains a short test program at the end of the file: The generic function make-instance takes the following arguments: There are four generic functions used in the function test: • set-header - required to initialize class and also defines the page title • add-element - used to insert a string that defines any type of HTML element • add-table - takes a list of lists and uses the list data to construct an HTML table • get-html-string - closes the stream and returns all generated HTML data as a string The first thing to notice in the function test is that the first argument for calling each of these generic functions is an instance of the class HTMLstream. You are free to also define a function, for example, add-element that does not take an instance of the class HTMLstream as the first function argument and calls to add-element will be routed correctly to the correct function definition. We will see that the macro defmethod acts similarly to defun except that it also allows us to define many methods (i.e., functions for a class) with the same function name that are differentiated by different argument types and possibly different numbers of arguments. ### Implementation of the HTMLstream Class The class HTMLstream is very simple and will serve as a reasonable introduction to CLOS programming. Later we will see more complicated class examples that use multiple inheritance. Still, this is a good example because the code is simple and the author uses this class frequently (some proof that it is useful!). The code fragments listed in this section are all contained in the file src/HTMLstream.lisp. We start defining a new class using the macro defclass that takes the following arguments: The class definition for HTMLstream is fairly simple: Here, the class name is HTMLstream, the list of super classes is an empty list (), the list of slot specifications contains only one slot specification for the slot out and there is only one class specification: a documentation string. Most CLOS classes inherit from at least one super class but we will wait until the next section to see examples of inheritance. There is only one slot (or instance variable) and we define an accessor variable with the same name as the slot name. This is a personal preference of mine to name read/write accessor variables with the same name as the slot. The method set-header initializes the string output stream used internally by an instance of this class. This method uses convenience macro with-accessors that binds a local set of local variable to one or more class slot accessors. We will list the entire method then discuss it: The first interesting thing to notice about the defmethod is the argument list: there are two arguments ho and title but we are constraining the argument ho to be either a member of the class HTMLstream or a subclass of HTMLstream. Now, it makes sense that since we are passing an instance of the class HTMLstream to this generic function (or method – I use the terms “generic function” and “method” interchangeably) that we would want access to the slot defined for this class. The convenience macro with-accessors is exactly what we need to get read and write access to the slot inside a generic function (or method) for this class. In the term ((out out)), the first out is local variable bound to the value of the slot named out for this instance ho of class HTMLstream. Inside the with-accessors macro, we can now use setf to set the slot value to a new string output stream. Note: we have not covered the Common Lisp type string-output-stream yet in this web book, but we will explain its use on the next page. By the time a call to the method set-header (with arguments of an HTMLstream instance and a string title) finishes, the instance has its slot set to a new string-output-stream and HTML header information is written to the newly created string output stream. Note: this string output stream is now available for use by any class methods called after set-header. There are several methods defined in the file src/HTMLstream.lisp, but we will look at just four of them: add-H1, add-element, add-table, and get-html-string. The remaining methods are very similar to add-H1 and the reader can read the code in the source file. As in the method set-header, the method add-H1 uses the macro with-accessors to access the stream output stream slot as a local variable out. In add-H1 we use the function princ that we discussed in Chapter on Input and Output to write HTML text to the string output stream: The method add-element is very similar to add-H1 except the string passed as the second argument element is written directly to the stream output stream slot: The method add-table converts a list of lists into an HTML table. The Common Lisp function princ-to-string is a useful utility function for writing the value of any variable to a string. The functions string-left-trim and string-right-trim are string utility functions that take two arguments: a list of characters and a string and respectively remove these characters from either the left or right side of a string. Note: another similar function that takes the same arguments is string-trim that removes characters from both the front (left) and end (right) of a string. All three of these functions do not modify the second string argument; they return a new string value. Here is the definition of the add-table method: The method get-html-string gets the string stored in the string output stream slot by using the function get-output-stream-string: CLOS is a rich framework for object oriented programming, providing a superset of features found in languages like Java, Ruby, and Smalltalk. I have barely scratched the surface in this short CLOS example for generating HTML. Later in the book, whenever you see calls to make-instance, that lets you know we are using CLOS even if I don’t specifically mention CLOS in the examples. We represent search space as a graph: nodes and links between the nodes. The following figure shows the simple graph that we use as an example, finding a route from node n1 to node n11: The following example code uses a heuristic for determining which node to try first from any specific location: move to the node that is closest spatially to the goal node. We see that this heuristic will not always work to produce the most efficient search but we will still get to the goal node. As an example in which the heuristic does not work, consider when we start at node n1 in the lower left corner of the figure. The search algorithm can add nodes n2 and n4 to the nodes to search list and will search using node n4 first since n4 is closer to the goal node n11 than node n2. In this case, the search will eventually need to back up trying the path n1 to n2. Despite this example of the heuristic not working to decrease search time, in general, for large search spaces (i.e., graphs with many nodes and edges) it can dramatically decrease search time. The main function Asearch** starting in line 5 extends to line 151 because all search utility functions are nested (lexically scoped) inside the mani function. The actual code for the main function **Asearch is in lines 150 and 151. The data representing nodes in this implementation is globally scoped (see the definitions on lines 155-165 in the “throw away test code” near the bottom of the file) and we set the property path-list to store the nodes directy connected to each node (set in function init-path-list in lines 36-52). I originally wrote this code in 1990 which explains it non-functional style using globally scoped node variables. The following example in the repl shows the calculation of the path that we saw in the figure of the graph search space. There are many types of search: breadth first as we used here, depth first, with heuristics to optimize search dependent on the type of search space. ## Network Programming Distributed computing is pervasive: you need to look no further than the World Wide Web, Internet chat, etc. Of course, as a Lisp programmer, you will want to do at least some of your network programming in Lisp! The previous editions of this book provided low level socket network programming examples. I decided that for this new edition, I would remove those examples and instead encourage you to “move further up the food chain” and work at a higher level of abstraction that makes sense for the projects you will likely be developing. Starting in the 1980s, a lot of my work entailed low level socket programming for distributed networked applications. As I write this, it is 2013, and there are better ways to structure distributed applications. Specifically, since many of the examples later in this book fetch information from the web and linked data sources, we will start be learning how to use Edi Weitz’s Drakma HTTP client library. In order to have a complete client server example we will also look briefly at Edi Weitz’s Hunchentoot web server that uses JSON as a data serialization format. I used to use XML for data serialization but JSON has many advantages: easier for a human to read and it plays nicely with Javascript code and some data stores like Postgres (new in versions 9.x), MongoDB, and CouchDB that support JSON as a native data format. The code snippets in the first two sections of this chapter are derived from examples in the Drackma and Hunchentoot documentation. ### An introduction to Drakma Edi Weitz’s Drakma library supports fetching data via HTTP requests. As you can see in the Drakma documentation, you can use this library for authenticated HTTP requests (i.e., allow you to access web sites that require a login), support HTTP GET and PUT operations, and deal with cookies. The top level API that we will use is drakma:http-request that returns multiple values. In the following example, I want only the first three values, and ignore the others like the original URI that was fetched and an IO stream object. We use the built-in Common Lisp macro multiple-value-setq: I manually formatted the last statement I entered in the last repl listing and I will continue to manually edit the repl listings in the rest of this book to make them more easily readable. The following shows some of the data bound to the variables data, http-response-code, and headers: The value of http-response-code is 200 which means that there were no errors: The HTTP response headers will be useful in many applications; for fetching the home page of my web site the headers are: We will use Drakma later in this book for several examples. In the next section we will write a web app using Hunchentoot and test it with a Drakma client. ### An introduction to Hunchentoot Edi Weitz’s Hunchentoot project is a flexible library for writing web applications and web services. We will also use Edi’s CL-WHO library in this section for generating HTML from Lisp code. Hunchentoot will be installed the first time you quick load it in the example code for this section: I will use only easy handler framework in the Hunchentoot examples in this section. I leave it to you to read the documentation on using custom acceptors after you experiment with the examples in this section. The following code will work for both multi-threading installations of SBCL and single thread installations (e.g., some default installations of SBCL on OS X): In lines 5 through 9 we create an use a new package that includes support for generating HTML in Lisp code (CL-WHO) and the Hunchentoot library). On line 11 we create an instance of an easy acceptor on port 3000 that provides useful default behaviors for providing HTTP services. The Hunchentoot macro define-easy-handler is used in lines 15 through 28 to define an HTTP request handler and add it to the easy acceptor instance. The first argument, my-greetings in this example, is an arbitrary name and the keyword :uri argument provides a URL pattern that the easy acceptor server object uses to route requests to this handler. For example, when you run this example on your computer, this URL routing pattern would handle requests like: In lines 17 through 28 we are using the CL-WHO library to generate HTML for a web page. As you might guess, :html generates the outer <html></html> tags for a web page. Line 19 would generate HTML like: Lines 22 through 27 generate an HTML input form and line 28 displays any value generated when the user entered text in the input filed and clicked the submit button. Notice the definition of the argument name in line 1 in the definition of the easy handler. If the argument name is not defined, the nil value will be displayed in line 28 as an empty string. You should run this example and access the generated web page in a web browser, and enter text, submit, etc. You can also fetch the generated page HTML using the Drakma library that we saw in the last section. Here is a code snippet using the Drakma client library to access this last example: We will use both Drackma and Hunchentoot in the next section. ### Complete REST Client Server Example Using JSON for Data Serialization A reasonable way to build modern distributed systems is to write REST web services that serve JSON data to client applications. These client applications might be rich web apps written in Javascript, other web services, and applications running on smartphones that fetch and save data to a remote web service. We will use the cl-json Quicklisp package to encode Lisp data into a string representing JSON encoded data. Here is a quick example: The following list shows the contents of the file src/web-hunchentoot-json.lisp: This example is very similar to the web application example in the last section. The difference is that this application is not intended to be viewed on a web page because it returns JSON data as HTTP responses. The easy handler definition on line 8 specifies a handler argument name. In lines 12 and 19 we check to see if the value of the argument name is “cat” or “dog” and if it is, we return the appropriate JSON example data for those animals. If there is no match, the default cond clause starting on line 26 returns a warning string as a JSON encoded string. While running this test service, in one repl, you can ue the Drakma library in another repl to test it (not all output is shown in the next listing): You can use the cl-json library to decode a string containing JSON data to Lisp data: For most of my work, REST web services are “read-only” in the sense that clients don’t modify state on the server. However, there are use cases where a client application might want to; for example, letting clients add new animals to the last example. In line 4 we are defining an additional easy handler with a handler argument json-data. This data is assumed to be a string encoding of JSON data which is decoded into Lisp data in lines 6 and 7. We save the data to the global variable animal-hash. In this example, we are storing data sent from a client in an in-memory hash table. In a real application new data might be stored in a database. ### Network Programming Wrap Up You have learned the basics for writing web services and writing clients to use web services. Later, we will use web services written in Python by writing Common Lisp clients: we will wrap retrained deep learning models and access them from Common Lisp. ## Accessing Relational Databases There are good options for accessing relational databases from Common Lisp. Personally I almost always use Postgres and in the past I used either native foreign client libraries or the socket interface to Postgres. Recently, I decided to switch to CLSQL which provides a common interface for accessing Postgres, MySQL, SQLite, and Oracle databases. There are also several recent forks of CLSQL on github. We will use CLSQL in examples in this book. Hopefully while reading the Chapter on Quicklisp you installed CLSQL and the back end for one or more databases that you use for your projects. If you have not installed CLSQL yet, then please install it now: You also need to install one or more CLSQL backends, depending on which relational databases you use: The directory src/clsql_examples contains the standalone example files for this chapter. While I often prefer hand crafting SQL queries, there seems to be a general movement in software development towards the data mapper or active record design patterns. CLSQL provides Object Relational Mapping (ORM) functionality to CLOS. You will need to create a new database news in order to follow along with the examples in this chapter and later in this book. I will use Postgres for examples in this chapter and use the following to create a new database (my account is “markw” and the following assumes that I have Postgres configured to not require a password for this account when accessing the database from “localhost”): We will use three example programs that you can find in the src/clsql_examples directory in the book repository on github: • clsql_create_news_schema.lisp to create table “articles” in database “news” • clsql_write_to_news.lisp to write test data to table “articles” • clsql_read_from_news.lisp to read from the table “articles” The following listing shows the file src/clsql_examples/clsql_create_news_schema.lisp: In this repl listing, we create the database table “articles” using the function create-articles-table that we just defined: The following listing shows the file src/clsql_examples/clsql_write_to_news.lisp: You should load the file clsql_write_to_news.lisp one time in a repl to create the test data. The following listing shows file clsql_read_from_news.lisp: Loading the file clsql_read_from_news.lisp produces the following output: You can also embed SQL where clauses in queries: which produces this output: In this example, I am using a SQL like expression to perform partial text matching. ### Database Wrap Up You learned the basics for accessing relational databases. When I am designing new systems for processing data I like to think of my Common Lisp code as being purely functional: my Lisp functions accept arguments that they do not modify and return results. I like to avoid side effects, that is changing global state. When I do have to handle mutable state (or data) I prefer storing mutable state in an external database. I use this same approach when I use the Haskell functional programming language. ## Using MongoDB, Solr NoSQL Data Stores Non-relational data stores are commonly used for applications that don’t need either full relational algebra or must scale. The MongoDB example code is in the file src/loving_snippets/mongo_news.lisp. The Solr example code is in the subdirectories src/solr_examples. Brewer’s CAP theorem states that a distributed data storage system comprised of multiple nodes can be robust to two of three of the following guarantees: all nodes always have a Consistent view of the state of data, general Availablity of data if not all nodes are functioning, and Partition tolerance so clients can still communicate with the data storage system when parts of the system are unavailable because of network failures. The basic idea is that different applications have different requirements and sometimes it makes sense to reduce system cost or improve scalability by easing back on one of these requirements. A good example is that some applications may not need transactions (the first guarantee) because it is not important if clients sometimes get data that is a few seconds out of date. MongoDB allows you to choose consistency vs. availability vs. efficiency. I cover the Solr indexing and search service (based on Lucene) both because a Solr indexed document store is a type of NoSQL data store and also because I believe that you will find Solr very useful for building systems, if you don’t already use it. We will design the examples in this chapter so that they can be reused in the last chapter in this book on Information Gathering. ### MongoDB The following discussion of MongoDB is based on just my personal experience, so I am not covering all use cases. I have used MongoDB for: • Small clusters of MongoDB nodes to analyze social media data, mostly text mining and sentiment analysis. In all cases for each application I ran MongoDB with one write master (i.e., I wrote data to this one node but did not use it for reads) and multiple read-only slave nodes. Each slave node would run on the same server that was usually performing a single bit of analytics. • Multiple very large independent clusters for web advertising. Problems faced included trying to have some level of consistency across data centers. Replica sets were used within each data center. • Running a single node MongoDB instance for low volume data collection and analytics. One of the advantages of MongoDB is that it is very “developer friendly” because it supports ad-hoc document schemas and interactive queries. I mentioned that MongoDB allows you to choose consistency vs. availability vs. efficiency. When you perform MongoDB writes you can specify some granularity of what constitutes a “successful write” by requiring that a write is performed at a specific number of nodes before the client gets acknowledgement that the write was successful. This requirement adds overhead to each write operation and can cause writes to fail if some nodes are not available. The MongoDB online documentation is very good. You don’t have to read it in order to have fun playing with the following Common Lisp and MongoDB examples, but if you find that MongoDB is a good fit for your needs after playing with these examples then you should read the documentation. I usually install MongoDB myself but it is sometimes convenient to use a hosting service. There are several well regarded services and I have used MongoHQ. At this time there is no official Common Lisp support for accessing MongoDB but there is a useful project by Alfons Haffmans’ cl-mongo that will allow us to write Common Lisp client applications and have access to most of the capabilities of MongoDB. The file src/mongo_news.lisp contains the example code used in the next three sessions. #### Adding Documents The following repl listing shows the cl-mongo APIs for creating a new document, adding elements (attributes) to it, and inserting it in a MongoDB data store: In this example, three string attributes were added to a new document before it was saved. #### Fetching Documents by Attribute We will start by fetchng and pretty-printing all documents in the collection articles and fetching all articles a list of nested lists where the inner nested lists are document URI, title, and text: Output for these two functions looks like: By reusing the function article-results->lisp-data defined in the last section, we can also search for JSON documents using regular expressions matching attribute values: I set the limit to return a maximum of ten documents. If you do not set the limit, this example code only returns one search result. The following repl listing shows the results from calling function search-articles-text: I find using MongoDB to be especially effective when experimenting with data and code. The schema free JSON document format, using interactive queries using the mongo shell, and easy to use client libraries like clouchdb for Common Lisp will let you experiment with a lot of ideas in a short period of time. The following listing shows the use of the interactive mongo shell. The database news is the database used in the MongoDB examples in this chapter; you will notice that I also have other databases for other projects on my laptop: Line 1 of this listing shows starting the mongo shell. Line 4 shows how to list all databases in the data store. In line 13 I select the database “news” to use. Line 15 prints out the names of all collections in the current database “news”. Line 18 prints out all documents in the “articles” collection. You can read the documentation for the mongo shell for more options like selective queries, adding indices, etc. When you run a MongoDB service on your laptop, also try the admin interface on http://localhost:28017/. ### A Common Lisp Solr Client The Lucene project is one of the most widely used Apache Foundation projects. Lucene is a flexible library for preprocessing and indexing text, and searching text. I have personally used Lucene on so many projects that it would be difficult to count them. The Apache Solr Project adds a network interface to the Lucene text indexer and search engine. Solr also adds other utility features to Lucene: • While Lucene is a library to embed in your programs, Solr is a complete system. • Solr provides good defaults for preprocessing and indexing text and also provides rich support for managing structured data. • Provides both XML and JSON APIs using HTTP and REST. • Supports faceted search, geospatial search, and provides utilities for highlighting search terms in surrounding text of search results. • If your system ever grows to a very large number of users, Solr supports scaling via replication. I hope that you will find the Common Lisp example Solr client code in the following sections helps you make Solr part of large systems that you write using Common Lisp. #### Installing Solr Download a binary Solr distribution and un-tar or un-zip this Solr distribution, cd to the distribution directory, then cd to the example directory and run: You can access the Solr Admin Web App at http://localhost:8983/solr/#/. This web app can be seen in the following screen shot: There is no data in the Solr example index yet, so following the Solr tutorial instructions: You will learn how to add documents to Solr directly in your Common Lisp programs in a later section. Assuming that you have a fast Internet connection so that downloading Solr was quick, you have hopefully spent less than five or six minutes getting Solr installed and running with enough example search data for the Common Lisp client examples we will play with. Solr is a great tool for storing, indexing, and searching data. I recommend that you put off reading the official Solr documentation for now and instead work through the Common Lisp examples in the next two sections. Later, if you want to use Solr then you will need to carefully read the Solr documentation. #### Solr’s REST Interface The Solr REST Interface Documentation documents how to perform search using HTTP GET requests. All we need to do is implement this in Common Lisp which you will see is easy. Assuming that you have Solr running and the example data loaded, we can try searching for documents with, for example, the word “British” using the URL http://localhost:8983/solr/select?q=British. This is a REST request URL and you can use utilities like curl or wget to fetch the XML data. I fetched the data in a web browser, as seen in the following screen shot of a Firefox web browser (I like the way Firefox formats and displays XML data): The attributes in the returned search results need some explanation. We indexed several example XML data files, one of which contained the following XML element that we just saw as a search result: So, the search result has the same attributes as the structured XML data that was added to the Solr search index. Solr’s capability for indexing structured data is a superset of just indexing plain text. If for example we were indexing news stories, then example input data might look like: With this example, a search result that returned this document as a result would return attributes id, title, and text, and the values of these three attributes. By default the Solr web service returns XML data as seen in the last screen shot. For our examples, I prefer using JSON so we are going to always add a request parameter wt=json to all REST calls. The following screen shot shows the same data returned in JSON serialization format instead of XML format of a Chrome web browser (I like the way Chrome formats and displays JSON data with the JSONView Chrome Browser extension): You can read the full JSON REST Solr documentation later, but for our use here we will use the following search patterns: • http://localhost:8983/solr/select?q=British+One&wt=json - search for documents with either of the words “British” or “one” in them. Note that in URIs that the “+” character is used to encode a space character. If you wanted a “+” character you would encode it with “%2B” and a space character is encoded as “%20”. The default Solr search option is an OR of the search terms, unlike, for example, Google Search. • http://localhost:8983/solr/select?q=British+AND+one&wt=json - search for documents that contain both of the words “British” and “one” in them. The search term in plain text is “British AND one”. As we sawearlier in Network Programming it is fairly simple to use the drakma and cl-json Common Lisp libraries to call REST services that return JSON data. The function do-search defined in the next listing (all the Solr example code is in the file src/solr-client.lisp) constructs a query URI as we saw in the last section and uses the Drackma library to perform an HTTP GET operation and the cl-json library to parse the returned string containing JSON data into Lisp data structures: This example code does return the search results as Lisp list data; for example: I might modify the search function to return just the fetched documents as a list, discarding the returned Solr meta data: There are a few more important details if you want to add Solr search to your Common Lisp applications. When there are many search results you might want to fetch a limited number of results and then “page” through them. The following strings can be added to the end of a search query: • &rows=2 this example returns a maximum of two “rows” or two query results. • &start=4 this example skips the first 4 available results A query that combines skipping results and limiting the number of returned results looks like this: #### Common Lisp Solr Client for Adding Documents In the last example we relied on adding example documents to the Solr search index using the directions for setting up a new Solr installation. In a real application, in addition to performing search requests for indexed documents you will need to add new documents from your Lisp applications. Using the Drakma we will see that it is very easy to add documents. We need to construct a bit of XML containing new documents in the form: You can specify whatever field names (attributes) that are required for your application. You can also pass multiple <doc></doc> elements in one add request. We will want to specify documents in a Lisp-like way: a list of cons values where each cons value is a field name and a value. For the last XML document example we would like an API that lets us just deal with Lisp data like: One thing to note: the attribute names and values must be passed as strings. Other data types like integers, floating point numbers, structs, etc. will not work. This is nicer than having to use XML, right? The first thing we need is a function to convert a list of cons values to XML. I could have used the XML Builder functionality in the cxml library that is available via Quicklisp, but for something this simple I just wrote it in pure Common Lisp with no other dependencies (also in the example file src/solr-client.lisp) : The macro with-output-to-string on line 2 of the listing is my favorite way to generate strings. Everything written to the variable stream inside the macro call is appended to a string; this string is the return value of the macro. The following function adds documents to the Solr document input queue but does not actually index them: You have noticed in line 3 that I am accessing a Solr server running on localhost and not a remote server. In an application using a remote Solr server you would need to modify this to reference your server; for example: For efficiency Solr does not immediately add new documents to the index until you commit the additions. The following function should be called after you are done adding documents to actually add them to the index: Notice that all we need is an empty element <commit></commit> that signals the Solr server that it should index all recently added documents. The following repl listing shows everything working together (I am assuming that the contents of the file src/solr-client.lisp has been loaded); not all of the output is shown in this listing: #### Common Lisp Solr Client Wrap Up Solr has a lot of useful features that we have not used here like supporting faceted search (drilling down in previous search results), geolocation search, and looking up indexed documents by attribute. In the examples I have shown you, all text fields are indexed but Solr optionally allows you fine control over indexing, spelling correction, word stemming, etc. Solr is a very capable tool for storing, indexing, and searching data. I have seen Solr used effectively on projects as a replacement for a relational database or other NoSQL data stores like CouchDB or MongoDB. There is a higher overhead for modifying or removing data in Solr so for applications that involve frequent modifications to stored data Solr might not be a good choice. ### NoSQL Wrapup There are more convenient languages than Common Lisp to use for accessing MongoDB. To be honest, my favorites are Ruby and Clojure. That said, for applications where the advantages of Common Lisp are compelling, it is good to know that your Common Lisp applications can play nicely with MongoDB. I am a polyglot programmer: I like to use the best programming language for any specific job. When we design and build systems with more than one programming language, there are several options to share data: • Use foreign function interfaces to call one language from another from inside one process. • Use a service architecture and send requests using REST or SOAP. • Use shared data stores, like relational databases, MongoDB, CouchDB and Solr. Hopefully this chapter and the last chapter will provide most of what you need for the last option. ## Natural Language Processing Natural Language Processing (NLP) is the automated processing of natural language text with several goals: • Determine the parts of speech (POS tagging) of words based on the surrounding words. • Detect if two text documents are similar. • Categorize text (e.g., is it about the economy, politics, sports, etc.) • Summarize text • Determine the sentiment of text • Detect names (e.g., place names, people’s names, product names, etc.) We will use a library that I wrote that performs POS tagging, categorization (classification), summarization, and detects proper names. My example code for this chapter is contained in separate Quicklisp projects located in the subdirectories: • src/fasttag: performs part of speech tagging and tokenizes text • src/categorize_summarize: performs categorization (e.g., detects the topic of text is news, politics, economy, etc.) and text summarization • src/kbnlp: the top level APIs for my pure Common Lisp natural language processing (NLP) code. In later chapters we will take a different approach by using Python deep learning models for NLP that we call as a web service. I use both approaches in my own work. I worked on this Lisp code, and also similar code in Java, from about 2001 to 2011, and again in 2019 for my application for generating knowledge graph data automatically (this is an example in a later chapter). I am going to begin the next section with a quick explanation of how to run the example code. If you find the examples interesting then you can also read the rest of this chapter where I explain how the code works. The approach that I used in my library for categorization (word counts) is now dated. I recommend that you consider taking Andrew Ng’s course on Machine Learning on the free online Coursera system and then take one of the Coursera NLP classes for a more modern treatment of NLP. In addition to the code for my library you might also find the linguistic data in src/linguistic_data useful. ### Loading and Running the NLP Library I repackaged the NLP example code into one long file. The code used to be split over 18 source files. The code should be loaded from the src/kbnlp directory: This also loads the projects in src/fasttag and src/categorize_summarize. Unfortunately, it takes a minute or two to load the required linguistic data so I recommend creating a Lisp image that can be reloaded to avoid the time required to load the data: In line 1 in this repl listing, I use the SBCL built-in function save-lisp-and-die to create the Lisp image file. Using save-lisp-and-die is a great technique to use whenever it takes a while to set up your work environment. Saving a Lisp image for use the next time you work on a Common Lisp project is reminiscent of working in Smalltalk where your work is saved between sessions in an image file. You can now start SBCL with the NLP library and data preloaded using the Lisp image that you just created: At the end of the file src/knowledgebooks_nlp.lisp in comments is some test code that processes much more text so that a summary is also generated; here is a bit of the output you will see if you load the test code into your repl: The top-level function make-text-object takes one required argument that can be either a string containing text or an array of strings where each string is a word or punctuation. Function make-text-object has two optional keyword parameters: the URL where the text was found and a title. In line 2, we check if this function was called with a string containing text in which case the function words-from-string is used to tokenize the text into an array of string tokens. Line two defines the local variable txt-obj with the value of a new text object with only three slots (attributes) defined: text, url, and title. Line 4 sets the slot text-tags to the part of speech tokens using the function part-of-speech-tagger. We use the function find-names-places in line 8 to get person and place names and store these values in the text object. In lines 11 through 17 we use the function get-word-list-category to set the categories in the text object. In line 18 we similarly use the function summarize to calculate a summary of the text and also store it in the text object. We will discuss these NLP helper functions throughout the rest of this chapter. The function make-text-object returns a struct that is defined as: ### Part of Speech Tagging This tagger is the Common Lisp implementation of my FastTag open source project. I based this project on Eric Brill’s PhD thesis (1995). He used machine learning on annotated text to learn tagging rules. I used a subset of the tagging rules that he generated that were most often used when he tested his tagger. I hand coded his rules in Lisp (and Ruby, Java, and Pascal). My tagger is less accurate, but it is fast - thus the name FastTag. If you just need part of speech tagging (and not summarization, categorization, and top level APIs used in the last section) you can load:  (ql:quickload "fasttag")  You can find the tagger implementation in the function part-of-speech-tagger. We already saw sample output from the tagger in the last section: The following table shows the meanings of the tags and a few example words: Tag Definition Example words CC Coord Conjuncn and, but, or NN Noun, sing. or mass dog CD Cardinal number one, two NNS Noun, plural dogs, cats DT Determiner the, some NNP Proper noun, sing. Edinburgh EX Existential there there NNPS Proper noun, plural Smiths FW Foreign Word mon dieu PDT Predeterminer all, both IN Preposition of, in, by POS Possessive ending ’s JJ Adjective big PP Personal pronoun I, you, she JJR Adj., comparative bigger PP$ Possessive pronoun my, one’s
LS List item marker 1, One
MD Modal can, should
RP Particle up, off
WP$Possessive-Wh whose SYM Symbol +, %, & WRB Wh-adverb how, where TO “to” to$ Dollar sign \$
UH Interjection oh, oops
# Pound sign #
VB verb, base form eat, run
quote
VBD verb, past tense ate
VBG verb, gerund eating
( Left paren (
VBN verb, past part eaten
) Right paren )
VBP Verb, present eat
, Comma ,
VBZ Verb, present eats
. Sent-final punct . ! ?
WDT Wh-determiner which, that
: Mid-sent punct. : ; —
WP Wh pronoun who, what

The function part-of-speech-tagger loops through all input words and initially assigns the most likely part of speech as specified in the lexicon. Then a subset of Brill’s rules are applied. Rules operate on the current word and the previous word.

As an example Common Lisp implementation of a rule, look for words that are tagged as common nouns, but end in “ing” so they should be a gerand (verb form):

You can find the lexicon data in the file src/linguistic_data/FastTagData.lisp. This file is List code instead of plain data (that in retrospect would be better because it would load faster) and looks like:

I generated this file automatically from lexicon data using a small Ruby script. Notice that words can have more than one possible part of speech. The most common part of speech for a word is the first entry in the lexicon.

### Categorizing Text

The code to categorize text is fairly simple using a technique often called “bag of words.” I collected sample text in several different categories and for each category (like politics, sports, etc.) I calculated the evidence or weight that words contribute to supporting a category. For example, the word “president” has a strong weight for the category “politics” but not for the category “sports.” The reason is that the word “president” occurs frequently in articles and books about politics. The data file that contains the word weightings for each category is src/data/cat-data-tables.lisp. You can look at this file; here is a very small part of it:

If you only need categorization and not the other libraries developed in this chapter, you can just load this library and run the example in the comment at the bottom of the file categorize_summarize.lisp:

({lang=”lisp”,linenos=off} (ql:quickload “categorize_summarize”) (defvar x “President Bill Clinton <<2 pages text no shown>> “) (defvar words1 (myutils:words-from-string x)) (print words1) (setq cats1 (categorize_summarize:categorize words1)) (print cats1) (defvar sum1 (categorize_summarize:summarize words1 cats1)) (print sum1)

Let’s look at the implementation, starting with creating hash tables for storing word count data for each category or topic:

This file was created by a simple Ruby script (not included with the book’s example code) that processes a list of sub-directories, one sub-directory per category. The following listing shows the implementation of function get-word-list-category that calculates category tags for input text:

On thing to notice in this listing is lines 11 through 15 where I define a nested function list-sort that takes a list of sub-lists and sorts the sublists based on the second value (which is a number) in the sublists. I often nest functions when the “inner” functions are only used in the “outer” function.

Lines 2 through 9 define several local variables used in the outer function. The global variable categoryHashtables is a list of word weighting score hash tables, one for each category. The local variable category-score-accumulation-array is initialized to an array containing the number zero in each element and will be used to “keep score” of each category. The highest scored categories will be the return value for the outer function.

Lines 17 through 27 are two nested loops. The outer loop is over each word in the input word array. The inner loop is over the number of categories. The logic is simple: for each word check to see if it has a weighting score in each category’s word weighting score hash table and if it is, increment the matching category’s score.

The local variable ss is set to an empty list on line 28 and in the loop in lines 29 through 38 I am copying over categories and their scores when the score is over a threshold value of 0.01. We sort the list in ss on line 39 using the inner function and then return the categories with a score greater than the median category score.

### Detecting People’s Names and Place Names

The code for detecting people and place names is in the top level API code in the package defined in src/kbnlp. This package is loaded using:

The functions that support identifying people’s names and place names in text are in the Common Lisp package kb nlp::

• find-names (words tags exclusion-list) – words is an array of strings for the words in text, tags are the parts of speech tags (from FastTag), and the exclusion list is a an array of words that you want to exclude from being considered as parts of people’s names. The list of found names records starting and stopping indices for names in the array words.
• not-in-list-find-names-helper (a-list start end) – returns true if a found name is not already been added to a list for saving people’s names in text
• find-places (words exclusion-list) – this is similar to find-names, but it finds place names. The list of found place names records starting and stopping indices for place names in the array words.
• not-in-list-find-places-helper (a-list start end) – returns true if a found place name is not already been added to a list for saving place names in text
• build-list-find-name-helper (v indices) – This converts lists of start/stop word indices to strings containing the names
• find-names-places (txt-object) – this is the top level function that your application will call. It takes a defstruct text object as input and modifies the defstruct text by adding people’s and place names it finds in the text. You saw an example of this earlier in this chapter.

I will let you read the code and just list the top level function:

In line 2 we are using the slot accessor text-text to fetch the array of word tokens from the text object. In lines 3, 4, and 5 we are doing the same for part of speech tags, place name indices in the words array, and person names indices in the words array.

In lines 6 through 11 we are using the function build-list-find-name-helper twice to construct the person names and place names as strings given the indices in the words array. We are also using the Common Lisp built-in function remove-duplicates to get rid of duplicate names.

In lines 12 through 16 we are discarding any persons names that do not contain a space, that is, only keep names that are at least two word tokens. Lines 17 through 19 define the return value for the function: a list of lists of people and place names using the function remove-shorter-names twice to remove shorter versions of the same names from the lists. For example, if we had two names “Mr. John Smith” and “John Smith” then we would want to drop the shorter name “John Smith” from the return list.

### Summarizing Text

The code for summarizing text is located in the directory src/categorize_summarize and can be loaded using:

The code for summarization depends on the categorization code we saw earlier.

There are many applications for summarizing text. As an example, if you are writing a document management system you will certainly want to use something like Solr to provide search functionality. Solr will return highlighted matches in snippets of indexed document field values. Using summarization, when you add documents to a Solr (or other) search index you could create a new unindexed field that contains a document summary. Then when the users of your system see search results they will see the type of highlighted matches in snippets they are used to seeing in Google, Bing, or DuckDuckGo search results, and, they will see a summary of the document.

Sounds good? The problem to solve is getting good summaries of text and the technique used may have to be modified depending on the type of text you are trying to summarize. There are two basic techniques for summarization: a practical way that almost everyone uses, and an area of research that I believe has so far seen little practical application. The techniques are sentence extraction and abstraction of text into a shorter form by combining and altering sentences. We will use sentence extraction.

How do we choose which sentences in text to extract for the summary? The idea I had in 1999 was simple. Since I usually categorize text in my NLP processing pipeline why not use the words that gave the strongest evidence for categorizing text, and find the sentences with the largest number of these words. As a concrete example, if I categorize text as being “politics”, I identify the words in the text like “president”, “congress”, “election”, etc. that triggered the “politics” classification, and find the sentences with the largest concentrations of these words.

Summarization is something that you will probably need to experiment with depending on your application. My old summarization code contained a lot of special cases, blocks of commented out code, etc. I have attempted to shorten and simplify my old summarization code for the purposes of this book as much as possible and still maintain useful functionality.

The function for summarizing text is fairly simple because when the function summarize is called by the top level NLP library function make-text-object, the input text has already been categorized. Remember from the example at the beginning of the chapter that the category data looks like this:

This category data is saved in the local variable cats on line 4 of the following listing.

The nested loops in lines 8 through 33 look a little complicated, so let’s walk through it. Our goal is to calculate an importance score for each word token in the input text and to then select a few sentences containing highly scored words. The outer loop is over the word tokens in the input text. For each word token we loop over the list of categories, looking up the current word in each category hash and incrementing the score for the current word token. As we increment the word token scores we also look for sentence breaks and save sentences.

The complicated bit of code in lines 16 through 32 where I construct sentences and their scores, and store sentences with a score above a threshold value in the list best-sentences. After the two nested loops, in lines 34 through 44 we simply sort the sentences by score and select the “best” sentences for the summary. The extracted sentences are no longer in their original order, which can have strange effects, but I like seeing the most relevant sentences first.

### Text Mining

Text mining in general refers to finding data in unstructured text. We have covered several text mining techniques in this chapter:

• Named entity recognition - the NLP library covered in this chapter recognizes person and place entity names. I leave it as an exercise for you to extend this library to handle company and product names. You can start by collecting company and product names in the files src/kbnlp/linguistic_data/names/names.companies and src/kbnlp/data/names/names.products and extend the library code.
• Categorizing text - you can increase the accuracy of categorization by adding more weighted words/terms that support categories. If you are already using Java in the systems you build, I recommend the Apache OpenNLP library that is more accurate than the simpler “bag of words” approach I used in my Common Lisp NLP library. If you use Python, then I recommend that you also try the NLTK library.
• Summarizing text.

In the next chapter I am going to cover another “data centric” topic: performing information gathering on the web. You will likely find some synergy between being able to use NLP to create structured data from unstructured text.

## Information Gathering

This chapter covers information gathering on the web using data sources and general techniques that I have found useful. When I was planning this new book edition I had intended to also cover some basics for using the Semantic Web from Common Lisp, basically distilling some of the data from my previous book “Practical Semantic Web and Linked Data Applications, Common Lisp Edition” published in 2011. However since a free PDF is now available for that book I decided to just refer you to my previous work if you are interested in the Semantic Web and Linked Data. You can also find the Java edition of this previous book on my web site.

Gathering information from the web in realtime has some real advantages:

• You don’t need to worry about storing data locally.
• Information is up to date (depending on which web data resources you choose to use).

There are also a few things to consider:

• Data on the web may have legal restrictions on its use so be sure to read the terms and conditions on web sites that you would like to use.
• Authorship and validity of data may be questionable.

### DBPedia Lookup Service

To load and run an example, try:

Wikipedia is a great resource to have on hand but I am going to show you in this section how to access the Semantic Web version or Wikipedia, DBPedia using the DBPedia Lookup Service in the next code listing that shows the contents of the example file dbpedia-lookup.lisp in the directory src/dbpedia:

I am only capturing the attributes for DBPedia URI, label and description in this example code. If you uncomment line 41 and look at the entire response body from the call to DBPedia Lookup, you can see other attributes that you might want to capture in your applications.

Here is a sample call to the function dbpedia:dbpedia-lookup (only some of the returned data is shown):

Wikipedia, and the DBPedia linked data for of Wikipedia are great sources of online data. If you get creative, you will be able to think of ways to modify the systems you build to pull data from DPPedia. One warning: Semantic Web/Linked Data sources on the web are not available 100% of the time. If your business applications depend on having the DBPedia always available then you can follow the instructions on the DBPedia web site to install the service on one of your own servers.

### Web Spiders

When you write web spiders to collect data from the web there are two things to consider:

• Make sure you read the terms of service for web sites whose data you want to use. I have found that calling or emailing web site owners explaining how I want to use the data on their site usually works to get permission.
• Make sure you don’t access a site too quickly. It is polite to wait a second or two between fetching pages and other assets from a web site.

We have already used the Drakma web client library in this book. See the files src/dbpedia/dbpedia-lookup.lisp (covered in the last section) and src/solr_examples/solr-client.lisp (covered in the Chapter on NoSQL). Paul Nathan has written library using Drakma to crawl a web site with an example to print out links as they are found. His code is available under the AGPL license at articulate-lisp.com/src/web-trotter.lisp and I recommend that as a starting point.

I find it is sometimes easier during development to make local copies of a web site so that I don’t have to use excess resources from web site hosts. Assuming that you have the wget utility installed, you can mirror a site like this:

Both of these examples have a two-second delay between HTTP requests for resources. The option -m indicates to recursively follow all links on the web site. The -w 2 option delays for two seconds between requests. The option -mk converts URI references to local file references on your local mirror. The second example on line 2 is more convenient.

We covered reading from local files in the Chapter on Input and Output. One trick I use is to simply concatenate all web pages into one file. Assuming that you created a local mirror of a web site, cd to the top level directory and use something like this:

You can then open the file, search for text in in p, div, h1, etc. HTML elements to process an entire web site as one file.

### Using Apache Nutch

Apache Nutch, like Solr, is built on Lucene search technology. I use Nutch as a “search engine in a box” when I need to spider web sites and I want a local copy with a good search index.

Nutch handles a different developer’s use case over Solr which we covered in the Chapter on NoSQL. As we saw, Solr is an effective tool for indexing and searching structured data as documents. With very little setup, Nutch can be set up to automatically keep an up to date index of a list of web sites, and optionally follow links to some desired depth from these “seed” web sites.

You can use the same Common Lisp client code that we used for Solr with one exception; you will need to change the root URI for the search service to:

So the modified client code src/solr_examples/solr-client.lisp needs one line changed:

Early versions of Nutch were very simple to install and configure. Later versions of Nutch have been more complex, more performant, and have more services, but it will take you longer to get set up than earlier versions. If you just want to experiment with Nutch, you might want to start with an earlier version.

The OpenSearch.org web site contains many public OpenSearch services that you might want to try. If you want to modify the example client code in src/solr-client.lisp a good start is OpenSearch services that return JSON data and OpenSearch Community JSON formats web page is a good place to start. Some of the services on this web page like the New York Times service require that you sign up for a developer’s API key.

When I start writing an application that requires web data (no matter which programming language I am using) I start by finding services that may provide the type of data I need and do my initial development with a web browser with plugin support to nicely format XML and JSON data. I do a lot of exploring and take a lot of notes before I write any code.

### Wrap Up

I tried to provide some examples and advice in this short chapter to show you that even though other languages like Ruby and Python have more libraries and tools for gathering information from the web, Common Lisp has good libraries for information gathering also and they are easily used via Quicklisp.

## Using The CL Machine-Learning Library

The CL Machine-Learning (CLML) library was originally developed by MSI (NTT DATA Mathematical Systems Inc. in Japan) and is supported by many developers. You should visit the CLML web page for project documentation and follow the installation directions and read about the project before using the examples in this chapter. However if you just want to quickly try the following CLML examples then you can install CLML using Quicklisp:

The installation will take a while to run but after installation using the libraries via quickload is fast. You can now run the example Quicklisp project src/clml_examples:

Please be patient the first time you run this because the first time you load the example project, the one time installation of CLML will take a while to run but after installation then the example project loads quickly. CLML installation involves downloading and installing BLAS, LAPACK, and other libraries.

Other resources for CLML are the tutorials and contributed extensions that include support for plotting (using several libraries) and for fetching data sets.

Although CLML is fairly portable we will be using SBCL and we need to increase the heap space when starting SBCL when we want to use the CLML library:

You can refer to the documentation at https://github.com/mmaul/clml. This documentation lists the packages with some information for each package but realistically I keep the source code for CLML in an editor or IDE and read source code while writing code that uses CLML. I will show you with short examples how to use the KNN (K nearest neighbors) and SVM (support vector machines) APIs. We will not cover other useful CLML APIs like time series processing, Naive Bayes, PCA (principle component analysis) and general matrix and tensor operations.

Even though the learning curve is a bit steep, CLML provides a lot of functionality for machine learning, dealing with time series data, and general matrix and tensor operations.

The CLML project uses several data sets and since the few that we will use are small files, they are included in the book’s repository in directory machine_learning_data under the src directory. The first few lines of labeled_cancer_training_data.csv are:

The first line in the CSV data files specifies names for each attribute with the name of the last column being “Class” which here takes on values benign or malignant. Later, the goal will be to create models that are constructed from training data and then make predictions of the “Class” of new input data. We will look at how to build and use machine learning models later but here we concentrate on reading and using input data.

The example file clml_data_apis.lisp shows how to open a file and loop over the values for each row:

The function read-data defined in lines 11-19 uses the utility function clml.hjs.read-data:read-data-from-file to read a CSV (comma separated value) spreadsheet file from disk. The CSV file is expected to contain 10 columns (set in lines 17-18) with the first nine columns containing floating point values and the last column text data.

The function loop-over-and-print-data defined in lines 21-26 reads the CLML data set object, looping over each data sample (i.e., each row in the original spreadsheet file) and printing it.

In the next section we will use the same cancer data training file, and another test data in the same format to cluster this cancer data into similar sets, one set for non-malignant and one for malignant samples.

### K-Means Clustering of Cancer Data Set

We will now read the same University of Wisconsin cancer data set and cluster the input samples (one sample per row of the spreadsheet file) into similar classes. We will find after training a model that the data is separated into two clusters, representing non-malignant and malignant samples.

The function cancer-data-cluster-example-read-data defined in lines 33-47 is very similar to the function read-data in the last section except here we read in two data files: one for training and one for testing.

The function cluster-using-k-nn defined in lines 13-30 uses the training and test data objects to first train a model and then to test it with test data that was previously used for training. Notice how we call this function in line 47: the first two arguments are the two data set objects, the third is the string “Class” that is the label for the 10th column of the original spreadsheet CSV files, and the last argument is the type of distance measurement used to compare two data samples (i.e., comparing any two rows of the training CSV data file).

The following listing shows the output from running the last code example:

### SVM Classification of Cancer Data Set

We will now reuse the same cancer data set but use a different way to classify data into non-malignant and malignant categories: Support Vector Machines (SVM). SVMs are linear classifiers which means that they work best when data is linearly separable. In the case of the cancer data, there are nine dimensions of values that (hopefully) predict one of the two output classes (or categories). If we think of the first 9 columns of data as defining a 9-dimensional space, then SVM will work well when a 8-dimensional hyperplane separates the samples into the two output classes (categories).

To make this simpler to visualize, if we just had two input columns, that defines a two-dimensional space, and if a straight line can separate most of the examples into the two output categories, then the data is linearly separable so SVM is a good technique to use. The SVM algorithm is effectively determining the parameters defining this one-dimensional line (or in the cancer data case, the 9-dimensional hyperspace).

What if data is not linearly separable? Then use the backpropagation neural network code in the chapter “Backpropagation Neural Networks” or the deep learning code in the chapter “Using Armed Bear Common Lisp With DeepLearning4j” to create a model.

SVM is very efficient so it often makes sense to first try SVM and if trained models are not accurate enough then use neural networks, including deep learning.

The following listing of file clml_svm_classifier.lisp shows how to read data, build a model and evaluate the model with different test data. In line 15 we use the function clml.svm.mu:svm that requires the type of kernel function to use, the training data, and testing data. Just for reference, we usually use Gaussian kernel functions for processing numeric data and linear kernel functions for handling text in natural language processing applications. Here we use a Gaussian kernel.

The function cancer-data-svm-example-read-data defined on line 40 differs from how we read and processed data earlier because we need to separate out the positive and negative training examples. The data is split in the lexically scoped function in lines 42-52. The last block of code in lines 54-82 is just top-level test code that gets executed when the file clml_svm_classifier.lisp is loaded.

The sample code prints the prediction values for the test data which I will not show here. Here are the last four lines of output showing the cumulative statistics for the test data:

### CLML Wrap Up

The CLML machine learning library is under fairly active development and I showed you enough to get started: understanding the data APIs and examples for KNN clustering and SVM classification.

A good alternative to CLML is MGL that supports backpropagation neural networks, boltzmann machines, and gaussian processes.

In the next two chapters we continue with the topic of machine learning with backpropagation andf Hopfield neural networks.

## Backpropagation Neural Networks

Let’s start with an overview of how these networks work and then fill in more detail later. Backpropagation networks are trained by applying training inputs to the network input layer, propagate values through the network to the output neurons, compare the errors (or differences) between these propagated output values and the training data output values. These output errors are backpropagated though the network and the magnitude of backpropagated errors are used to adjust the weights in the network.

The example we look at here uses the plotlib package from an earlier chapter and the source code for the example is the file loving_snippet/backprop_neural_network.lisp.

We will use the following diagram to make this process more clear. There are four weights in this very simple network:

• W1,1 is the floating point number representing the connection strength between input_neuron1 and output_neuron1
• W2,1 connects input_neuron2 to output_neuron1
• W1,2 connects input_neuron1 to output_neuron2
• W2,2 connects input_neuron2 to output_neuron2

Before any training the weight values are all small random numbers.

Consider a training data element where the input neurons have values [0.1, 0.9] and the desired output neuron values are [0.9 and 0.1], that is flipping the input values. If the propagated output values for the current weights are [0.85, 0.5] then the value of the first output neuron has a small error abs(0.85 - 0.9) which is 0.05. However the propagated error of the second output neuron is high: abs(0.5 - 0.1) which is 0.4. Informally we see that the weights feeding input output neuron 1 (W1,1 and W2,1) don’t need to be changed much but the neuron that feeding input neuron 2 (W1,2 and W2,2) needs modification (the value of W2,2 is too large).

Of course, we would never try to manually train a network like this but it is important to have at least an informal understanding of how weights connect the flow of value (we will call this activation value later) between neurons.

In this neural network see in the first figure we have four weights connecting the input and output neurons. Think of these four weights forming a four-dimensional space where the range in each dimension is constrained to small positive and negative floating point values. At any point in this “weight space”, the numeric values of the weights defines a model that maps the inputs to the outputs. The error seen at the output neurons is accumulated for each training example (applied to the input neurons). The training process is finding a point in this four-dimensional space that has low errors summed across the training data. We will use gradient descent to start with a random point in the four-dimensional space (i.e., an initial random set of weights) and move the point towards a local minimum that represents the weights in a model that is (hopefully) “good enough” at representing the training data.

This process is simple enough but there are a few practical considerations:

• Sometimes the accumulated error at a local minimum is too large even after many training cycles and it is best to just restart the training process with new random weights.
• If we don’t have enough training data then the network may have enough memory capacity to memorize the training examples. This is not what we want: we want a model with just enough memory capacity (as represented by the number of weights) to form a generalized predictive model, but not so specific that it just memorizes the training examples. The solution is to start with small networks (few hidden neurons) and increase the number of neurons until the training data can be learned. In general, having a lot of training data is good and it is also good to use as small a network as possible.

In practice using backpropagation networks is an iterative process of experimenting with the size of a network.

In the example program (in the file backprop_neural_network.lisp) we use the plotting library developed earlier to visualize neuron activation and connecting weight values while the network trains.

The following three screen shots from running the function test3 defined at the bottom of the file backprop_neural_network.lisp illustrate the process of starting with random weights, getting random outputs during initial training, and as delta weights are used to adjust the weights in a network, then the training examples are learned:

In the last figure the initial weights are random so we get random mid-range values at the output neurons.

As we start to train the network, adjusting the weights, we start to see variation in the output neurons as a function of what the inputs are.

In the last figure the network is trained sufficiently well to map inputs [0, 0, 0, 1] to output values that are approximately [0.8, 0.2, 0.2, 0.3] which is close to the expected value [1, 0, 0, 0].

The example source file backprop_neural_network.lisp is long so we will only look at the more interesting parts here. Specifically we will not look at the code to plot neural networks using plotlib.

The activation values of individual neurons are limited to the range [0, 1] by first calculating their values based on the sum activation values of neurons in the previous layer times the values of the connecting weights and then using the Sigmoid function to map the sums to the desired range. The Sigmoid function and the derivative of the Sigmoid function (dSigmoid) look like:

Here are the definitions of these functions:

The function NewDeltaNetwork creates a new neual network object. This code allocates storage for input, hidden, output layers (I sometimes refer to neuron layers as “slabs”), and the connection weights. Connection weights are initialized to small random values.

In the following listing the function DeltaLearn processes one pass through all of the training data. Function DeltaLearn is called repeatedly until the return value is below a desired error threshold. The main loop over each training example is implemented in lines 69-187. Inside this outer loop there are two phases of training for each training example: a forward pass propagating activation from the input neurons to the output neurons via any hidden layers (lines 87-143) and then the weight correcting backpropagation of output errors while making small adjustments to weights (lines 148-187):

The function DeltaRecall in the next listing can be used with a trained network to calculate outputs for new input values:

We saw three output plots earlier that were produced during a training run using the following code:

Here the function test3 defines training data for a very small test network for a moderately difficult function to learn: to rotate the values in the input neurons to the right, wrapping around to the first neuron. The start of the main loop in line calls the training function 3000 times, creating a plot of the network every 400 times through the main loop.

Backpropagation networks have been used sucessfully in production for about 25 years. In the next chapter we will look at a less practical type of network, Hopfield networks, that are still interesting because the in some sense Hopfield networks model how our brains work. In the final chapter we will look at deep learning neural networks.

## Hopfield Neural Networks

A Hopfield network (named after John Hopfield) is a recurrent network since the flow of activation through the network has loops. These networks are trained by applying input patterns and letting the network settle in a state that stores the input patterns.

The example code is in the file src/loving_snippets/Hopfield_neural_network.lisp.

The example we look at recognizes patterns that are similar to the patterns seen in training examples and maps input patterns to a similar training input pattern. The following figure shows output from the example program showing an original training pattern, a similar pattern with one cell turned on and other off, and the reconstructed pattern:

To be clear, we have taken one of the original input patterns the network has learned, slightly altered it, and applied it as input to the network. After cycling the network, the slightly scrambled input pattern we just applied will be used as an associative memory key, look up the original pattern, and rewrite to input values with the original learned pattern. These Hopfield networks are very different than backpropagation networks: neuron activation are forced to values of -1 or +1 and not be differentiable and there are no separate output neurons.

The next example has the values of three cells modified from the original and the original pattern is still reconstructed correctly:

This last example has four of the original cells modified:

The following example program shows a type of content-addressable memory. After a Hopfield network learns a set of input patterns then it can reconstruct the original paterns when shown similar patterns. This reconstruction is not always perfecrt.

The following function Hopfield-Init (in file Hopfield_neural_network.lisp) is passed a list of lists of training examples that will be remembered in the network. This function returns a list containing the data defining a Hopfield neural network. All data for the network is encapsulated in the list returned by this function, so multiple Hopfield neural networks can be used in an application program.

In lines 9-12 we allocate global arrays for data storage and in lines 14-18 the training data is copied.

The inner function adjustInput on lines 20-29 adjusts data values to values of -1.0 or +1.0. In lines 31-33 we are initializing all of the weights in the Hopfield network to zero.

The last nested loop, on lines 35-52, calculates the autocorrelation weight matrix from the input test patterns.

On lines 54-56, the function returns a representation of the Hopfield network that will be used later in the function HopfieldNetRecall to find the most similar “remembered” pattern given a new (fresh) input pattern.

The following function HopfieldNetRecall iterates the network to let it settle in a stable pattern which we hope will be the original training pattern most closely resembling the noisy test pattern.

The inner (lexically scoped) function deltaEnergy defined on lines 9-12 calculates a change in energy from old input values and the autocorrelation weight matrix. The main code uses the inner functions to iterate over the input cells, possibly modifying the cell at index i delta energy is greater than zero. Remember that the lexically scoped inner functions have access to the variables for the number of inputs, the number of training examples, the list of training examples, the input cell values, tempoary storage, and the Hopfield network weights.

Function test in the next listing uses three different patterns for each test. Note that only the last pattern gets plotted to the output graphics PNG file for the purpose of producing figures for this chapter. If you want to produce plots of other patterns, edit just the third pattern defined on line AAAAA. The following plotting functions are inner lexically scoped so they have access to the data defined in the enclosing let expression in lines 16-21:

• plotExemplar - plots a vector of data
• plot-original-inputCells - plots the original input cells from training data
• plot-inputCells - plots the modified input cells (a few cells randomly flipped in value)
• modifyInput - scrambles training inputs

The plotting functions in lines 23-62 use the plotlib library to make the plots you saw earlier. The function modifyInput in lines 64-69 randomly flips the values of the input cells, taking an original pattern and slightly modifying it.

Hopfield neural networks, at least to some extent, seem to model some aspects of human brains in the sense that they can function as content-addressable (also called associative) memories. Ideally a partial input pattern from a remembered input can reconstruct the complete original pattern. Another interesting feature of Hopfield networks is that these memories really are stored in a distributed fashion: some of the weights can be randomly altered and patterns are still remembered, but with more recall errors.

## Using Python Deep Learning Models In Common Lisp

In older editions of this book I had an example of using the Java DeepLearning4J deep learning library using Armed Bear Common Lisp, implemented in Java. I no longer use hybrid Java and Common Lisp applications in my own work and I decided to remove this example and replace it with two projects that use simple Python web services that act as wrappers for state of the art deep learning models with Common Lisp clients in the subdirectories:

• src/spacy_web_client: use the spaCy deep learning models for general NLP. I sometimes use my own pure Common Lisp NLP libraries we saw in earlier chapters and sometimes I use a Common Lisp client calling deep learning libraries like spaCy and TensorFlow.
• src/coref_web_client: coreference or anaphora resolution is the act of replacing pronouns in text with the original nouns that they refer to. This has traditionally been a very difficult and only partially solved problem until recent advances in deep learning models like BERT.

### Setting up the Python Web Services Used in this Chapter

You will need python and pip installed on your system. The source e code for the Python web services is found in the directory loving-common-lisp/python.

### Installing the spaCY NLP Services

I assume that you have some familiarity with using Python. If not, you will still be able to follow these directions assuming that you have the utilities pip, and python installed. I recommend installing Python and Pip using Anaconda.

The server code is in the subdirectory python/python_spacy_nlp_server where you will work when performing a one time initialization. After the server is installed you can then run it from the command line from any directory on your laptop.

I recommend that you use virtual Python environments when using Python applications to separate the dependencies required for each application or development project. Here I assume that you are running in a Python version 3.6 or higher environment. First you must install the dependencies:

Then change directory to the subdirectory python/python_spacy_nlp_server in the git repo for this book and install the NLP server:

Once you install the server, you can run it from any directory on your laptop or server using:

I use deep learning models written in Python using TensorFlow or PyTorch and provide Python web services that can be used in applications I write in Haskell or Common Lisp using web client interfaces for the services written in Python. While it is possible to directly embed models in Haskell and Common Lisp, I find it much easier and developer friendly to wrap deep learning models I use a REST services as I have done here. Often deep learning models only require about a gigabyte of memory and using pre-trained models has lightweight CPU resource needs so while I am developing on my laptop I might have two or three models running and available as wrapped REST services. For production, I configure both the Python services and my Haskell and Common Lisp applications to start automatically on system startup.

This is not a Python programming book and I will not discuss the simple Python wrapping code but if you are also a Python developer you can easily read and understand the code.

### Installing the Coreference NLP Services

I recommend that you use virtual Python environments when using Python applications to separate the dependencies required for each application or development project. Here I assume that you are running in a Python version 3.6 environment. First you should install the dependencies:

As I write this chapter the neuralcoref model and library require a slightly older version of SpaCy (the current latest version is 2.1.4).

Then change directory to the subdirectory python/python_coreference_anaphora_resolution_server in the git repo for this book and install the coref server:

Once you install the server, you can run it from any directory on your laptop or server using:

While. as we saw in the last example, it is possible to directly embed models in Haskell and Common Lisp, I find it much easier and developer friendly to wrap deep learning models I use a REST services as I have done here. Often deep learning models only require about a gigabyte of memory and using pre-trained models has lightweight CPU resource needs so while I am developing on my laptop I might have two or three models running and available as wrapped REST services. For production, I configure both the Python services and my Haskell and Common Lisp applications to start automatically on system startup.

This is not a Python programming book and I will not discuss the simple Python wrapping code but if you are also a Python developer you can easily read and understand the code.

### Common Lisp Client for the spaCy NLP Web Services

Before looking at the code, I will show you typical output from running this example:

The client library is implemented in the file src/spacy_web_client/spacy.lisp:

On line 3 we define base URL for accessing the spaCy eb service, assuming that it is running on your laptop and not a remote server. On line 5 we define a defstruct named spacy-data that has two fields: a list of entities in the input text and a list of word tokens in the input text.

The function spacy-client builds a query string on lines 10-12 that consists of the base-url and the input query text URL encoded. The drakma library, that we used before, is used to make a HTTP request from the Python spaCy server. Lines 14-15 uses the flexi-streams package to convert raw byte data to UTF8 characters. Lines 16-17 use the json package to parse the UTF8 encoded string, getting two lists of strings. I left the debug printout expression in line 18 so that you can see the results of parsing the JSON data. The function make-spacy-data was generated for us by the defstruct statement on line 5.

### Common Lisp Client for the Coreference NLP Web Services

Let’s look at some typical output from this example, then we will look at the code:

Notice that pronouns in the input text are correctly replaced by the noun phrases that the pronoun refer to.

The implementation for the core client is in the file src/coref_web_client/coref.lisp:

This code is similar to the example in the last section for setting up a call to http-request but is simpler: here the Python coreference web service accepts a string as input and returns a string as output with pronouns replaced by the nouns or noun phrases that they refer to. The example in the last section had to parse returned JSON data, this example does not.

### Python Interop Wrap-up

Much of my professional work in the last five years involved deep learning models and currently most available software is written in Python. While there are available libraries for calling Python code from Common Lisp, these libraries tend to not work well for Python code using libraries like TensorFlow, spaCy, PyTorch, etc., especially if the Python code is configured to use GPUs via CUDA of special hardware like TPUs. I find it simpler to simply wrap functionality implemented in Python as a simple web service.

## Automatically Generating Data for Knowledge Graphs

We develop a complete application. The Knowledge Graph Creator (KGcreator) is a tool for automating the generation of data for Knowledge Graphs from raw text data. We will see how to create a single standalone executable file using SBCL Common Lisp. The application can also be run during development from a repl. This application also implements a web application interface.

Data created by KGcreator generates data in two formats:

• Neo4j graph database format (text format)

This example application works by identifying entities in text. Example entity types are people, companies, country names, city names, broadcast network names, political party names, and university names. We saw earlier code for detecting entities in the chapter on natural language processing (NLP) and we will reuse this code. We will discuss later three strategies for reusing code from different projects.

When I originally wrote KGCreator I intended to develop a commercial product. I wrote two research prototypes, one in Common Lisp (the example in this chapter) and one in Haskell (which I also use as an example in my book Haskell Tutorial and Cookbook. I decided to open source both versions of KGCreator and if you work with Knowledge Graphs I hope you find KGCreator useful in your work.

The following figure shows part of a Neo4j Knowledge Graph created with the example code. This graph has shortened labels in displayed nodes but Neo4j offers a web browser-based console that lets you interactively explore Knowledge Graphs. We don’t cover setting up Neo4j here so please use the Neo4j documentation. As an introduction to RDF data, the semantic web, and linked data you can get free copies of my two books Practical Semantic Web and Linked Data Applications, Common Lisp Edition and Practical Semantic Web and Linked Data Applications, Java, Scala, Clojure, and JRuby Edition.

Here is a detail view:

### Implementation Notes

As seen in the file src /kgcreator/package.lisp this application uses several other packages:

The implementation of the packages shown on line 3 were in a previous chapter. The package myutils are mostly miscellaneous string utilities that we won’t look at here; I leave it to you to read the source code.

As seen in the configuration file src/kgcreator/kgcreator.asd we split the implementation of the application into four source files:

The application is separated into four source files:

• kgcreator.lisp: top level APIs and functionality. Uses the code in neo4j.lisp and rdf.lisp. Later we will generate a standalone application that uses these top level APIs
• neo4j.lisp: generates Cyper text files that can be imported into Neo4j
• rdf.lisp: generates RDF text data that can be loaded or imported into RDF data stores
• web.lisp: a simple web application for running KGCreator

### Generating RDF Data

I leave it to you find a tutorial on RDF data on the web, or you can get a PDF for my book “Practical Semantic Web and Linked Data Applications, Common Lisp Edition” and read the tutorial sections on RDF.

RDF data is comprised of triples, where the value for each triple are a subject, a predicate, and an object. Subjects are URIs, predicates are usually URIs, and objects are either literal values or URIs. Here are two triples written by this example application:

The following listing of the file src/kgcreator/rdf.lisp generates RDF data:

You can load all of KGCreator but just execute the test function at the end of this file using:

This code works on a list of paired files for text data and the meta data for each text file. As an example, if there is an input text file test123.txt then there would be a matching meta file test123.meta that contains the source of the data in the file test123.txt. This data source will be a URI on the web or a local file URI. The top level function rdf-from-files takes an output file path for writing the generated RDF data and a list of pairs of text and meta file paths.

A global variable /rdf-nodes-hash*** will be used to remember the nodes in the RDF graph as it is generated. Please note that the function **rdf-from-files** is not re-entrant: it uses the global **/rdf-nodes-hash* so if you are writing multi-threaded applications it will not work to execute the function rdf-from-files simultaneously in multiple threads of execution.

The function rdf-from-files (and the nested functions) are straightforward. I left a few debug printout statements in the code and when you run the test code that I left in the bottom of the file, hopefully it will be clear what rdf.lisp is doing.

### Generating Data for the Neo4j Graph Database

Now we will generate Neo4J Cypher data. In order to keep the implementation simple, both the RDF and Cypher generation code starts with raw text and performs the NLP analysis to find entities. This example could be refactored to perform the NLP analysis just one time but in practice you will likely be working with either RDF or NEO4J and so you will probably extract just the code you need from this example (i.e., either the RDF or Cypher generation code).

Before we look at the code, let’s start with a few lines of generated Neo4J Cypher import data:

The following listing of file src/kgcreator/neo4j.lisp is similar to the code that generated RDF in the last section:

You can load all of KGCreator but just execute the test function at the end of this file using:

### Implementing the Top Level Application APIs

The code in the file src/kgcreator/kgcreator.lisp uses both rdf.lisp and neo4j.lisp that we saw in the last two sections. The function get-files-and-meta looks at the contents of an input directory to generate a list of pairs, each pair containing the path to a text file and the meta file for the corresponding text file.

We are using the opts package to parse command line arguments. This will be used when we build a single file standalone executable file for the entire KGCreator application, including the web application that we will see in a later section.

You can load all of KGCreator but just execute the three test functions at the end of this file using:

### Implementing The Web Interface

When we build a standalone single file application for KGCreator, we include a simple web application interface that allows users to enter input text and see generated RDF and Neo4j Cypher data.

The file src/kgcreator/web.lisp uses the libraries cl-who hunchentoot parenscript that we used earlier. The function write-files-run-code** (lines 8-43) takes raw text, and writes generated RDF and Neo4j Cypher data to local temporary files that are then read and formatted to HTML for display. The code in rdf.lisp and neo4j.lisp is file oriented, and I wrote web.lisp as an afterthought so it was easier writing temporary files than refactoring rdf.lisp and neo4j.lisp to write to strings.

You can load all of KGCreator and start the web application using:

You can access the web app at http://localhost:3000.

### Creating a Standalone Application Using SBCL

When I originally wrote KGCreator I intended to develop a commercial product so it was important to be able to create standalone single file executables. This is simple to do using SBCL:

As an example, you could run the application on the command line using:

### KGCreator Wrap Up

When developing applications or systems using Knowledge Graphs it is useful to be able to quickly generate test data which is the primary purpose of KGCreator. A secondary use is to generate Knowledge Graphs for production use using text data sources. In this second use case you will want to manually inspect the generated data to verify its correctness or usefulness for your application.

## Book Wrapup

Congratulations for finishing this book!

I love programming in Lisp languages with concise code and a bottom-up approach to development. I hope you now also share this enthusiasm with me.

Common Lisp is sometimes criticised as not having as many useful libraries as some newer languages like Python and Java, and this is a valid criticism. That said, I hope the wide variety of examples in this book will convince you that Common Lisp is a good choice for many types of programming projects.

I would like to thank you for reading my book and I hope that you enjoyed it. As I mentioned in the Introduction I have been using Common Lisp since the mid-1980s, and other Lisp dialects for longer than that. I have always found something almost magical developing in Lisp. Being able to extend the language with macros and using the development technique of building a mini-language in Lisp customized for an application enables programmers to be very efficient in their work. I have usually found that this bottom-up development style helps me deal with software complexity because the lower level functions tend to get well tested while the overall system being developed is not yet too complex to fully understand. Later in the development process these lower level functions and utilities almost become part of the programming language and the higher level application logic is easier to understand because you have fewer lines of code to fit inside your head during development.

I think that unless a programmer works in very constrained application domains, it often makes sense to be a polyglot programmer. I have tried, especially in the new material for this fourth edition, to give you confidence that Common Lisp is good for both general software development language and also as “glue” to tie different systems together.

Mark Watson

## Appendix A - My Common Lisp Development Setup

I spend some effort getting my Common Lisp development system setup for my tastes. Hopefully you will find some good ideas here that will help you customize your development system.

### Setup for Local Quicklisp Projects

I created my setup from a blog article written by Zach Beane. Please read Zach’s blog article before continuing to read my setup notes here.

I configure ASDF2 and Quicklisp to look for all of my local Common Lisp projects in my github repo directory common-lisp/lisp; my ~/.config/common-lisp/source-registry.conf.d/projects.conf file looks like:

In my home directory I keep all of my github repos in ~/GITHUB. Here is what my GITHUB/common-lisp/lisp directory looks like at the moment I am writing this:

Note that except for the project for my web site AIsentience.net, all the libraries in the last figure are from this book.

As an example, from any directory on my laptop I can access any libraries stored as subdirectories of my ~/GITHUB/common-lisp/lisp directory:

TBD: fix last example

### Load Data Files Relative to Path of Source File that Uses Data

When you want to use your Common Lisp projects as libraries (e.g., with Quicklisp) there is a potential problem if your code requires static data files. I like to get the directory of the current source file and then use relative path offsets to find data files. For example, in my plotting library in the source file plotlib.lisp I get the current source directory:

Note that this code works both for loading plotlib as a source file and for compiling the source code before loading. Now, when I need access to the font files used by plotlib I then have the correct directory path:

I also use this trick for the linguistic files used in the KBnlp example code in this book.