| <html> | |
| <head> | |
| <title>LISP Tutorial Lecture 4: Imperative Programming</title> | |
| </head> | |
| <body bgcolor=ffffff> | |
| <h1>LISP Tutorial Lecture 4: Imperative Programming</h1> | |
| <h2>Imperative vs Functional Programming</em> | |
| <p>The fragment of LISP we have learned so far is purely functional. | |
| We program by defining mathematical functions. Programming this way | |
| has the benefit of <em>referential transparency</em>, which means that | |
| an experession has the same value and the same behavior, no matter | |
| where it is located, and how many times it is invoked. For example, | |
| the following function always returns 4 when an input 2 is supplied: | |
| <pre> | |
| (defun double (x) (* 2 x)) | |
| </pre> | |
| Such programs are easy to develop and debug. The only effect of calling | |
| a function is the returned value. Functions become a lot harder to | |
| understand and debug when we allow them to produce <em>side effects</em>, that | |
| is, affecting subsequent computation in ways other than returning a value. | |
| This style of programming, in which side effect is not only permissible | |
| but is also the primary means by which we program, is | |
| called <em>imperative programming</em>. This is not something new, but | |
| is in fact the very kind of programming habits that you have acquired since | |
| you learned your first programming language (e.g. C/C++, Pascal, Java). | |
| Because of this, we intentionally leave the topic of imperative programming to | |
| the end of this series of tutorials. We do so since you already know so | |
| much about imperative programming, and since, in my taste, teaching it | |
| before teaching functional programming would only reinforce some of | |
| the bad habits programmers usually have, and thereby luring you to | |
| write C code with LISP, which, of course, make it harder to finish | |
| your assignment on time. | |
| <h2>Variables</h2> | |
| <p>Imperative programming is made possible by the notion of | |
| <em>program state</em>. The behavior of an expression depends | |
| on the exact state a program is in. In turn, the state of | |
| a program is defined by, guess what, <em>variables</em>. | |
| <p>Suppose we want to create a global counter to keep track of the | |
| times some computational events occur. | |
| Common LISP allows us to define global variables as follows. | |
| <pre> | |
| USER(7): (defparameter *counter* 0 "Counter to keep track of ....") | |
| *COUNTER* | |
| USER(8): (setf *counter* (1+ *counter*)) | |
| 1 | |
| USER(9): *counter* | |
| 1 | |
| USER(10): (setf *counter* (1+ *counter*)) | |
| 2 | |
| USER(11): *counter* | |
| 200 | |
| </pre> | |
| We use the <tt>defparameter</tt> special form to define | |
| a global variable <tt>*counter*</tt>, with zero as its | |
| initial value. We also decorate the declaration by a | |
| documentation string. We then use the <tt>setf</tt> | |
| special form to assign new values to the variable. | |
| The <tt>setf</tt> special form returns the new value of | |
| the variable. | |
| Lastly, evaluating the variable gives its current value. | |
| Notice that <tt>*counter*</tt> is evaluated to two different values | |
| at different point of time. This is something you will never see if | |
| you work with purely functional programs. | |
| <p>Suppose we actually want this counter to reset to zero when it | |
| reaches a user defined threshold. We would encapsulate this | |
| service into the following definitions: | |
| <pre> | |
| (defparameter *counter* 0 | |
| "Counter to keep track of ....") | |
| (defparameter *threshold* 4 | |
| "Counter will be reset to zero when its value reaches this threshold.") | |
| (defun counter-inc () | |
| "Increment global counter by one." | |
| (if (>= (1+ *counter*) *threshold*) | |
| (setf *counter* 0) | |
| (setf *counter* (1+ *counter*)))) | |
| (defun counter-value () | |
| "Return current value of global counter." | |
| *counter*) | |
| (defun counter-threshold () | |
| "Return current threshold of global counter." | |
| *threshold*) | |
| </pre> | |
| <pre> | |
| USER(24): (counter-value) | |
| 0 | |
| USER(25): (counter-inc) | |
| 1 | |
| USER(26): (counter-inc) | |
| 2 | |
| USER(27): (counter-inc) | |
| 3 | |
| USER(28): (counter-threshold) | |
| 4 | |
| USER(29): (counter-inc) | |
| 0 | |
| </pre> | |
| <p>The function <tt>counter-inc</tt> can also be defined as follows: | |
| <pre> | |
| (defun counter-inc () | |
| "Increment global counter by one." | |
| (if (>= (1+ *counter*) *threshold*) | |
| (setf *counter* 0) | |
| (incf *counter*))) | |
| </pre> | |
| <h2>Sequencing</h2> | |
| <p>With the possibility of state alteration, we also need a new kind | |
| of programming construct --- <em>sequencing</em>. This allows us to | |
| perform multiple state-alterating operations, one after another. | |
| For example, we might want to introduce another function to our global | |
| counter abstraction: a function to modify the value of <tt>*threshold*</tt> | |
| on the fly: | |
| <pre> | |
| (defun counter-set-threshold (th) | |
| "Set counter threshold to TH." | |
| (setf *threshold* th) | |
| (if (>= *counter* *threshold*) | |
| (setf *counter* 0)) | |
| *threshold*) | |
| </pre> | |
| The function sets the global value of <tt>*threshold*</tt> to a new value, | |
| and then checks if the current counter value has exceeded the new threshold. | |
| If the check succeeds, then the counter is reset to zero. Lastly, the | |
| function evaluates and returns the last expression, which is simply the | |
| new value of <tt>*threshold*</tt>. Notice that | |
| in this example the body of a function is no longer one expression, but | |
| a sequence of expressions. They are evaluated in order, and the value | |
| of the last expression is returned as a value of the sequence. | |
| The effect is demonstrated as in the following trace: | |
| <pre> | |
| USER(2): (counter-value) | |
| 0 | |
| USER(3): (counter-inc) | |
| 1 | |
| USER(4): (counter-inc) | |
| 2 | |
| USER(5): (counter-inc) | |
| 3 | |
| USER(6): (counter-inc) | |
| 0 | |
| USER(7): (counter-inc) | |
| 1 | |
| USER(8): (counter-inc) | |
| 2 | |
| USER(9): (counter-set-threshold 2) | |
| 0 | |
| USER(10): (counter-value) | |
| 0 | |
| </pre> | |
| <p>In fact, forms like <tt>let</tt>, <tt>let*</tt>, <tt>when</tt> and | |
| <tt>unless</tt> all admit sequences as their bodies. The <tt>cond</tt> | |
| form allows sequencing in the body of each alternative. The exception | |
| is <tt>if</tt>, due to its syntax. However, you can always get around | |
| by introducing a <tt>let</tt> form in the alternatives or by using | |
| other conditional forms. | |
| <p>Before we move on, notice that we can rewrite the <tt>counter-inc</tt> | |
| function as follows: | |
| <pre> | |
| (defun counter-inc () | |
| "Increment global counter by one." | |
| (if (>= (1+ *counter*) *threshold*) | |
| (setf *counter* 0) | |
| (incf *counter*))) | |
| </pre> | |
| The <tt>(incf x)</tt> form is simply a shorthand for <tt>(setf x (+ x 1))</tt>. | |
| In general, the following are useful shorthands when developing imperative | |
| programs: | |
| <p> | |
| <table border=1> | |
| <tr> | |
| <th>Shorthand</th><th>Meaning</th> | |
| </tr> | |
| <tr> | |
| <td><tt>(incf x delta)</tt></td> | |
| <td><tt>(setf x (+ x delta))</td> | |
| </tr> | |
| <tr> | |
| <td><tt>(incf x)</tt></td> | |
| <td><tt>(incf x 1)</tt></td> | |
| </tr> | |
| <tr> | |
| <td><tt>(decf x delta)</tt></td> | |
| <td><tt>(setf x (- x delta))</tt></td> | |
| </tr> | |
| <tr> | |
| <td><tt>(decf x)</tt></td> | |
| <td><tt>(decf x 1)</tt></td> | |
| </tr> | |
| <tr> | |
| <td><tt>(push e x)</tt></td> | |
| <td><tt>(setf x (cons e x))</tt></td> | |
| </tr> | |
| <tr> | |
| <td><tt>(pop x)</tt></td> | |
| <td><tt>(let ((e (first x))) (setf x (rest x)) e)</tt></td> | |
| </tr> | |
| </table> | |
| <p><hr><b>Exercise:</b> Create a global stack abstraction, with | |
| interface functions for performing pushing and poping. | |
| <hr> | |
| <h2>Closures</h2> | |
| <p>The above method for defining an abstraction is not good enough. | |
| For one, the global variables are not encapsulated. There is | |
| nothing to forbid a careless user to change the value of <tt>*counter*</tt> | |
| in ways violating the invariants of the counter abstraction. | |
| To enforce this, we make use of <em>local variables</em> and <em>closures</em>. | |
| <p>As one would expect, the names introduced by a <tt>let</tt> form turns | |
| out not to be a name binding to some immutable values. The names refer | |
| to local variables. Such variables follow typical <em>lexical scoping | |
| rules</em>, so that LISP always looks up the innermost variable definition | |
| when a variable name is to be evaluated. | |
| <p>What is more interesting is that, due to the ability to return | |
| functions as values, the local variable has a life span longer than | |
| the expression defining it. Consider the following example: | |
| <pre> | |
| USER(20): (setf inc (let ((counter 0)) | |
| #'(lambda () | |
| (incf counter)))) | |
| #<Interpreted Closure (unnamed) @ #x53688a> | |
| USER(21): (funcall inc) | |
| 1 | |
| USER(22): (funcall inc) | |
| 2 | |
| USER(23): (funcall inc) | |
| 3 | |
| </pre> | |
| We assign a value to the global variable <tt>inc</tt>. That value | |
| is obtained by first | |
| defining local variable <tt>counter</tt> using <tt>let</tt>, | |
| and then within the lexical scope of the local variable, | |
| a lambda expression is evaluated, | |
| thereby creating an annonymous function, which is returned as a value | |
| to be assigned to <tt>inc</tt>. The most interesting part | |
| is in the body of that lambda expression --- it increments | |
| the value of the local variable <tt>counter</tt>! When the lambda | |
| expression is returned, the local variable persists, and is accessible | |
| only through the annonymous function. | |
| <p>The thing to remember from this example is that, in other kinds | |
| of languages like Pascal and C/C++ the lexical scope of a local | |
| variable somehow coincide with its life span. After executation | |
| passes beyond the boundary of a lexical scope, all the local | |
| variables defined within it cease to exist. This is not true | |
| in languages supporting higher-order functions, in particular, | |
| expressions that return functions as values. | |
| However, that is not to say that lexical scoping does not | |
| hold in such languages. In the contrary, lexical scoping is | |
| enforced strictly, and therefore the only place from which | |
| you can alter the value of <tt>counter</tt> is, as every | |
| true believer of lexical scoping would agree, within the lexical | |
| scope of the variable --- the lambda expression. As a result, | |
| the counter state is effectively encapsulated. The only | |
| way to modify it is by going through the annonymous function stored | |
| in <tt>inc</tt>. The technical term to refer to this <em>thing</em> | |
| that is stored in <tt>inc</tt>, this thing that at the same time | |
| captures both the definition of a function and the variables | |
| referenced within the function body is called a <em>function closure</em>. | |
| <p>What if we want to define multiple interface functions for | |
| the encapsulated counter? Simple, just return all of them: | |
| <pre> | |
| USER(34): (setf list-of-funcs (let ((counter 0)) | |
| (list #'(lambda () | |
| (incf counter)) | |
| #'(lambda () | |
| (setf counter 0))))) | |
| (#<Interpreted Closure (unnamed) @ #x5408e2> | |
| #<Interpreted Closure (unnamed) @ #x540912>) | |
| USER(35): (setf inc (first list-of-funcs)) | |
| #<Interpreted Closure (unnamed) @ #x5408e2> | |
| USER(36): (setf reset (second list-of-funcs)) | |
| #<Interpreted Closure (unnamed) @ #x540912> | |
| USER(37): (funcall inc) | |
| 1 | |
| USER(38): (funcall inc) | |
| 2 | |
| USER(39): (funcall inc) | |
| 3 | |
| USER(40): (funcall reset) | |
| 0 | |
| USER(41): (funcall inc) | |
| 1 | |
| </pre> | |
| <p><hr><b>Exercise:</b> Define an encapsulated global stack. | |
| <hr> | |
| <h2>Poor-Man's Object</h2> | |
| <p>Having only one instance of this encapsulated counter abstraction | |
| is not good enough. Imagine cases when we need multiple instances | |
| of such counters, each having its own state. Well, the answer | |
| is simple, we just evaluate the function-returning <tt>let</tt> | |
| form everytime we need a new instance of counter. Since, a new | |
| local variable will be created everytime we evaluate the <tt>let</tt> | |
| form, the function closure that is returned each time will be | |
| associated with a different incarnation of the local variable <tt>counter</tt>. | |
| To automate this process, of course we define a <em>constructor</em> | |
| for such closures: | |
| <pre> | |
| (defun make-counter () | |
| "Create a new instance of a counter object." | |
| (let ((counter 0)) | |
| (list #'(lambda () | |
| (incf counter)) | |
| #'(lambda () | |
| (setf counter 0))))) | |
| </pre> | |
| Notice how this allows us to maintain independently encapsulated states: | |
| <pre> | |
| USER(44): (setf c1 (make-counter)) | |
| (#<Interpreted Closure (:INTERNAL MAKE-COUNTER) @ #x543f00> | |
| #<Interpreted Closure (:INTERNAL MAKE-COUNTER) @ #x543f30>) | |
| USER(44): (setf c2 (make-counter)) | |
| (#<Interpreted Closure (:INTERNAL MAKE-COUNTER) @ #x543f62> | |
| #<Interpreted Closure (:INTERNAL MAKE-COUNTER) @ #x543f92>) | |
| USER(45): (funcall (first c1)) | |
| 1 | |
| USER(46): (funcall (first c1)) | |
| 2 | |
| USER(47): (funcall (second c1)) | |
| 0 | |
| USER(48): (funcall (first c2)) | |
| 1 | |
| USER(49): (funcall (first c2)) | |
| 2 | |
| USER(50): (funcall (first c2)) | |
| 3 | |
| USER(51): (funcall (first c1)) | |
| 1 | |
| USER(52): (funcall (first c1)) | |
| 2 | |
| USER(53): (funcall (second c2)) | |
| 0 | |
| USER(54): (funcall (first c1)) | |
| 3 | |
| </pre> | |
| <p>To make invoking counter interface functions easier, we can | |
| define the following shorthands: | |
| <pre> | |
| (defun counter-increment (counter) | |
| "Increment counter." | |
| (funcall (first counter))) | |
| (defun counter-reset (counter) | |
| "Reset counter." | |
| (funcall (second counter))) | |
| </pre> | |
| And now we have an all-rounded counter abstraction. | |
| <pre> | |
| USER(56): (counter-increment c1) | |
| 4 | |
| USER(57): (counter-reset c1) | |
| 0 | |
| </pre> | |
| <p>The moral of this store is that, function closures are <em>encapsulated | |
| states</em>. They are a poor-man's version of objects, which, after all, | |
| are nothing but encapsulated states. (Yes, I am aware that Common LISP | |
| has a Common LISP Object System (CLOS), and there is no point of | |
| using closures in this manner if all we want is simply object orientation. | |
| But No, I want you to understand what higher-order functions buy | |
| you, and how they serve as a building block for other advanced | |
| programming language constructs. Lastly, I don't want you to spend | |
| time struggling to learn yet another object system.) | |
| <p><hr><b>Exercise:</b> Implement a constructor for your encapsulated | |
| stack abstraction. Define appropriate shorthands for | |
| convenient invocation of interface functions. | |
| <hr> | |
| <h2>Iterative Constructs</h2> | |
| <p>To round off this tutorial, we discuss something that you | |
| know so much about --- iterations. We start with something | |
| very simple: | |
| <pre> | |
| USER(1): (dotimes (i 10) (print i)) | |
| 0 | |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| NIL | |
| </pre> | |
| The <tt>(dotimes (<em>i</em> <em>n</em>) | |
| <em>body</em>)</tt> form executes <em>body</em> <em>N</em> times. | |
| In addition, it defines a local variable <em>i</em>, which receives | |
| an integer value ranging from <em>0</em> to <em>n-1</em>. | |
| The body of the form could be a sequence of expressions. The form | |
| returns <tt>NIL</tt>. The <tt>(print <em>x</em>)</tt> form prints | |
| the LISP object <em>x</em> to the console. | |
| <p>A similar construct is defined for iterating through a list: | |
| <pre> | |
| USER(2): (dolist (i '(a b c d e)) (print i)) | |
| A | |
| B | |
| C | |
| D | |
| E | |
| NIL | |
| </pre> | |
| <p>The most general looping construct is the <tt>do</tt> form: | |
| <pre> | |
| (defun fibonacci (n) | |
| "Compute the N'th Fibonacci number." | |
| (do ((f1 0 f2) | |
| (f2 1 (+ f1 f2)) | |
| (i 0 (1+ i))) | |
| ((= i n) f2) | |
| ; empty body | |
| )) | |
| </pre> | |
| The first list following the <tt>do</tt> keyword is a list of | |
| local variables and their initializations and update forms. | |
| Each member of this list has the format <tt>(<em>var</em> | |
| <em>init-form</em> <em>update-form</em>)</tt>. | |
| Within this loop are defined three local variables <tt>f1</tt>, | |
| <tt>f2</tt> and <tt>i</tt>. The three initialization forms | |
| 0, 1 and 0 are evaluated first, and then assigned to the | |
| three locals simultaneously. In each subsequent iteration, | |
| the three update forms <tt>f2</tt>, <tt>(+ f1 f2)</tt> and | |
| <tt>(1+ i)</tt> will be evaluated first, and then the values | |
| are assigned to the three local variables simultaneously. | |
| The second list following the <tt>do</tt> keyword | |
| (i.e. <tt>((= i n) f2)</tt>) has the general format of | |
| <tt>(<em>exit-condition</em> <em>return-form</em>)</tt>. | |
| The exit condition <tt>(= i n)</tt> is checked after | |
| the initialization is done, or after the update is performed | |
| in subsequent iterations. If the test succeeds, then the | |
| return form is evaluated, and its value is returned. Otherwise, | |
| the body of the <tt>do</tt> form, which in this case is empty, | |
| will be executed with the updated value of the local variables. | |
| <p>Indefinite looping can be achieved using the <tt>(loop <em>body</em>)</tt> | |
| form. One may exit from such loop using the <tt>return-from</tt> form: | |
| <pre> | |
| (defun fib (n) | |
| "Compute the N'th Fibonacci number." | |
| (let ((f1 0) | |
| (f2 1) | |
| (i 0)) | |
| (loop | |
| (if (= i n) | |
| (return-from fib f2)) | |
| ; empty body | |
| (psetf f1 f2 | |
| f2 (+ f1 f2) | |
| i (1+ i))))) | |
| </pre> | |
| The <tt>fib</tt> function has the same meaning as the <tt>fibonacci</tt> | |
| function coded in terms of <tt>do</tt>. The <tt>psetf</tt> is a | |
| variation of <tt>setf</tt> that implements "parallel" assignment. | |
| </body> | |
| </html> |