Thursday, June 28, 2012

Possessions obsessions

So listening to Papa Roach, "Between Angels and Insects".

"There's no money. There's no possessions, only obsession."

I'm struck with the thought that my obsession, yes it is, with video games and more particularly the kind where you accumulate 'stuff' is a sublimation of materialism to assuage the pain of not being able to accumulate real world 'stuff' for so long. I wouldn't call myself deprived but during my childhood we never 'kept up with the Jonses' nor made even a cursory attempt to and I was given a general impression that we were broke. However I went to a school district where 'the Jonses' were effectively idolized. I felt my family's purported lack, whether 'real' or not, and now I think it has perhaps had a lasting impact on my psyche. I feel compelled (yes, that's the right word) to play certain games. Not puzzle games, not shooters. I used to enjoy enforcing mastery on a difficult system (for a long time Gradius II was the best thing in the universe when it was new) but I'm not so good at twitch mechanics anymore. All that's left is really the grind for more ingame 'stuff' which, actually, I end up finding quite boring and not fun

So recognizing this drive, can I control it? Harness it? Expunge it as poison? Games have inherent value, yes, but not the way I tend to consume them.


Coming back and cleaning up the above into something approaching coherence I had the thought that I shouldn't blame my father (that's where the majority of my impression of destitution came from I suspect) as his parents were, my my admittedly faulty estimation, poor. I imagine it takes a solid generation to expunge that from the family's psyche.
I've also read the full lyrics, instead of just listening to them, and am struck by ... well, by the whole thing. I was going to look at a couple of lines but nevermind. Here's the whole thing.

Last word. I'm amused how the close-mindedness of Religion would deprive me of such insight. Rejecting things that don't immediately fall in line with your beliefs is idiocy no matter what terms you couch it in or justifications you give. If scripture is your excuse to reject something without considering its value then you devalue scripture.

Land of Lisp chapter 6

Whoops. Naughty me, I did the 6.5 post before the chapter 6 post. Well, 6.5 was more interesting and easier to write at the same time. So it got done first. Onward; pretend all the lambda navel-gazing hasn't happened yet.

Now this adventure game is pretty ugly, and very user unfriendly. Time to clean it up a bit. That's going to require some better I/O functions.

The basic screen printing functions are:
print: Prints one output per line, strings in quotes. Perfectly machine readable later.
print1: Dispenses with the newline
princ: Human readable output.
For reading input:
read: Just the basic Lisp input, parens and quotes required.
read-line: Reads until the user hits enter and takes the whole input verbatim as a string.
read-from-string: Just like read except it takes a string input instead of reading from the console.

With that it's time to learn one of the more powerful functions. eval takes input and parses it as code. So

executes the form with the (princ "bar") output that you'd expect. This is quite powerful but also dangerous. And it's dangerous in ways that are not necessarily immediately obvious. I'll get to that.

At this point we have all the capabilities to build our very own REPL. Rather like opening a DOS shell within a DOS shell. You might compare it to running Windows in a VM except that the VM handles a lot of background operations and that would be more akin to the next step in this chapter. To the point however, here's the dead simple code for a basic, nofrills, 'custom' REPL (custom in quotes because it's about as bog standard as it gets even though it's a REPL in a REPL).

That's all well and good but when we execute (my-repl) nothing really interesting happens. Visibly at least. Because, of course, the functions we've used have no functionality beyond the basic REPL. We haven't written any. So that's clearly the next step. Now is a good time to note that I'm storing the code for this custom REPL in a separate file because it becomes essentially a general use engine for running simple text adventures. The file will be linked at the bottom along with loading instructions (such as they are).

I'd also like to note in advance that I think the way the game-repl is implemented is a bad paradigm. It basically uses recursion to perform the 'loop' structure. I added a printout to the book's code to make this obvious; basically when you 'quit' you'll get a playback of all the commands entered. Now while this implementation is tiny compared to modern memory sizes it's important to note that recursion has some overhead (which is also made obvious by the printout). It literally does not matter here due to the scales involved, I want to stress that, but it's important to note the point. Maybe this small structural complaint is fixed later in the book, I dunno. But on with it.

First we want to be able to take input. So we build game-read.

Take a moment to look at the flet function quote-it. What does (list 'quote x) do? A heretofore undescribed complexity is that we've been using a shorthand when quoting. 'foo is the same as using the quote function as in (quote foo). So what quote-it does is create a list that is a form of the quote function. It literally quotes its input and returns it. It's important to note that this case doesn't require #'quote because it isn't being passed as a parameter to a higher order function; the full special form is created using list so it will get evaluated normally. So to describe the game-read function fully, first we read a raw line of input, then we create a string (because we requested it by specifying 'string) by concatenating parenthesis around the input. Then we read that string into the cmd variable. Then we quote the cdr of the entered command (if it's more than 1 list item) using mapcar and quote-it, cons the thing back together, and return that result.

Next, we need to evaluate what we just read.


Two things to note. First, I added the case expression. It's completely missing in the book. But I'm afraid 'pickup' is just awkward to me and since get is its own special form it needed to be handled specially by the evaluation function. So I select it with case and convert it to a 'pickup' verb instead. Additional verbs can be added to the case form as needed, though if there are many then a flet might be in order . Second the *allowed-commands* global I'm placing in the game data file. It's specific to the game so doesn't need to be in the custom REPL code. It's defined as (again, I added 'get' myself to get it past the member filter):

So this is pretty straightforward. The only complexity is what I added. An if test is performed to determine if the input verb (the car of the input expression) is allowed and it's either evaled or an error is generated.

Finally there's the output. This is the most complicated. As usual.

Some of the lines probably break in the wrong places which makes it boogers to read. I really need to find a decent scroll block to plug in here, but I'm lazy and have other things to do. Look it up in the code file if it bothers you. (Edit: Should look much better now that it's in gist!)

Basically what happens here is the input list to game-print is printed to a string value by prin1-to-string which works the same as prin1 but returns the string instead of printing it to screen. That string has parenthesis and spaces hacked off the ends by the obvious string-trim function and the output from that is coerced to a list of characters. Then tweak-text is called which handles capitalization (there's nothing new in the function so I'll leave figuring out the logic as an exercise... oh wait, char-upcase and char-downcase... surely those are completely obvious...) and the resultant list of character values is then coerced to a string, princed and a fresh-line is output. Phew.

Now, to plug this all together (with my aforementioned rudimentary stack trace):

So, if you input 'quit' the recursion ends and all the input cmds are re-output.. Dead simple.

As the last word, a caveat about eval. We've pretty thoroughly scrubbed the user input right? We only accept a few verbs past the filters in front of eval, only one of those is a special form command, and that one is re-written as a different verb with no special meanings. There's still a problem though. As with anything that one doesn't fully understand there's a backdoor, apparently, in the read functionality. The book doesn't go into detail but there are apparently read macros that allow all sorts of shenanigans. Like perhaps

I don't know if there's a way to disable those or not. I'm hoping the book will cover them in more detail shortly.

The files:
gameREPL.lisp
TheWizardAdventureGame.lisp

You'll want to do the following:

to get things running (using the correct paths of course).

Saturday, June 23, 2012

Land of Lisp chapter 6.5 - Lambda

Okay, the chapter (sort of) on lambda. Perhaps I'm dense, or inexperienced, or just plain stupid but I'm not sure I see what all the hype is. This (half) chapter, for all its hyperbole, does little to dispel the mist surrounding the importance of the lambda.

It begins with a discussion about how functions are first class values in Lisp. You can pass them around the same way you do any other variable (presumably you can edit them as well... (cdr #'myfunc) being the list of parameters perhaps? But now I'm talking about things I don't know...). This is well and good and useful. You can pass them on to higher order functions all over the place if need be.

To come back to lambda, the special form is

lambda is a macro, not a function, and returns an anonymous function (not a macro, or a llama). Because lambda is a macro it doesn't evaluate all of its parameters prior to execution, so the {code} passes in unaltered (I assume anyway) by the parser.

I suppose what I'm failing to understand is how this is more useful than, say, constructing an actual function (if you need it more than once) or simply placing code inline. For example:

Is functionally equivalent to

and

(I suppose both of those are really the same solution, one just explicitly recurses where the other lets mapcar deal with that complexity) Once I've defuned a function I can use it in multiple places. A lambda function is, by virtue of its anonymity, incapable of such feats (unless, again, I'm missing something?).

Now that I try to think about it though, there doesn't seem to be a C-like loop structure in Lisp. Not that I've gotten to yet anyway. If there is you should be able to simply put the (/ x 2) inside the loop directly. (Edit: There is, it's in the next chapter!)

Now, is the lambda code above 'cleaner'? That depends. A neophyte would probably say 'no'. The mapcar snippet is nearly as concise and more human readable (which is desirable) to a beginner. A programmer steeped in Lisp will, apparently, disagree.

Then of course there's the near-mysticism that the author gets into about Lisp growing out of lambda calculus and how it's really sort of the only function in Lisp, etc. Which is great if you live in an ivory tower and get a stipend for getting other people's brains in knots (especially if you still appear to know what you're talking about). Unfortunately, I don't see (yet?) how this makes Lisp superior to other languages. But. This is the first brush with it and clearly there's something here if the amount of ink spilled on it is any indication. So hopefully understanding will come shortly.

Friday, June 22, 2012

Land of Lisp chapter 5

Chapter 5 is exciting. We get to actually write a bit of an engine (if that's not glorifying it too much) for a text adventure game. Okay, it's 3 rooms and 4 objects and no interactions to speak of yet. That's not the good part. More content can be added easily enough by extending the global variables. But I'm getting ahead of myself.

One language syntax that was introduced is quasiquoting. Basically this is a syntax that allows you to embed bits of code inside a data list. This is familiar to me since I work with a scripting language that does this by default. In Lisp

notice the backtick instead of single quote. That indicates quasiquoting 'mode' (not sure mode is the right term in the same way it applies to data/code mode but whatever). The comma indicates the beginning of a code block and Lisp automatically returns to data mode once the list closes. In this case I could have left the parentheses around foo off, but I left them in to make the end of code mode more explicit.

In the builtin scripting language for UC4

So this might have been a concept unique to Lisp(s) once upon a time, but no longer.

The second bit of syntax is the use of #' to indicate that the following symbol is a function name. This is necessary because Common Lisp maintains separate namespaces for variables and functions. Apparently this means it is called a Lisp-2 language. This in comparison to Scheme which, as a Lisp-1 language, maintains a single namespace containing both functions and variables. So you couldn't have a variable named car in Scheme (car is a standard builtin function in Lisp, I assume it is in Scheme as well?).

There is also some more discussion of functional programming but that isn't why I'm working through this so I'm not going to spend more time on it.

This chapter also introduces the conceptual architecture for the Wizard's Adventure Game and constructs a good bit of basic functionality. We view the game as a mathematical graph; each room is a node and the paths between them are edges in the graph. Why this particularly matters enough to bleed ink on I don't rightly know but I'm not a game designer (yet?). It's as good as any visualization and probably better than some.Using the parlance of nodes and edges we proceed to build the tables for rooms and the paths between those rooms as global variables.

I'll link to the full (and developing, I'm not going to keep versions for each chapter) code for the game at the bottom. In the code above we have a pair of associative array... er, lists describing the nodes and the vital information for the paths. We also build a series of functions to pull out the specific room information. These functions (which I'm not going to bother copying in here, download the source if you're curious) use the assoc function to retrieve a specific element from the associative list.

which we can then pull the description from. We also created a list of objects and a list defining where those objects are located.

We also used the append function to join lists together. This is conceptually equivalent to string concatenation except it applies to lists. We used append in conjunction with apply basically to flatten out nested lists created by mapcar. mapcar is what's called a higher-order function because it takes another function as a parameter and does something with it. In this case, the function is executed against each item in a list

and the returns are consed together into a unified list.

The apply function is also higher-order and it takes a list of inputs and feeds them one piece at a time to the function parameter. This is a convenient way to remove a layer of nesting from a list, but I don't entirely grok the logic. I'll need to feel this one out some more.

In this case we apply-ed the append function to the nested lists created by mapcar to get a flat list of symbols that reads like text. One thing I forgot to discuss at the top is the deliberate use of symbols instead of strings. This isn't imposed by the language, but the language makes it much easier to work with lists of symbols instead of strings, apparently. We could certainly use the string data type for this, but then functions like cadr would work differently on them and would require more code.

We then proceed to take all these things and build a rudimentary user interface. Functions are defined for look, walk, and pickup. Of these, only pickup is really interesting; it uses push to add a variable to the front of the object locations associative list with the value of body. Since assoc only returns the first item in the list that matches this effectively hides the original entry and the item now is only visible in inventory (also a function built at the end of the chapter).

Here's the link to the code as it currently exists. Bear in mind that this will be built upon further in later chapters and I'm not going to bother keeping multiple copies. If you want chapter-by-chapter code buy the book.

Monday, June 18, 2012

Land of Lisp Chp 4

Chapter 4 covers exclusively boolean operations. It starts with a discussion of the only false data value in Lisp which is the empty set '(). This differs from Scheme, though the details of that aren't discussed as they're clearly outside the scope of the book. Note that it is represented in data mode because it is a data value, not a form.

To complicate matters (which seems to happen a lot in this chapter) '() isn't the only way to represent falsehood. This is a careful distinction which I'll come back to. The following are all false in Lisp

The first is just the empty list. The second resolves to an empty list due to the way Lisp parses forms. nil is actually a constant that resolves to 'nil and part of the Common Lisp spec is that 'nil and '() are equivalent. Why are all 4 deliberately set up this way? The book doesn't say. I suspect backwards or cross-dialect compatibility, but to be honest I don't really care right now. It is what it is, as my boss is fond of saying. The important thing is that an empty list is false, and any list that is not empty is true by definition (though in practice the 'nil can present some gotchas that will come up later). This lends Lisp to easy recursive processing of lists like so.

The above recursively cdrs to the end of the list and adds 1 for each symbol; the false branch of the if form returns 0 for the empty list at the end

Next up is if. Which has already been used but not discussed. It's hard to talk about boolean operations without 'if' in seemingly any language. Lisp's if is a bit stunted compared to something like a dialect of C. if only does one thing. Because of the way the command is structured

you can only evaluate one list. Which is a tad misleading since that one list could be a function form that does a million things or, as the book suggests, a call to progn which is glossed over here but apparently behaves similarly to an eval function. Still, it's an important thing to remember and it would tend to reinforce functional programming if that's your thing.

A key feature of if is that, like many other languages, it performs short circuit evaluation. The book spends a lot of ink on this, but I shan't bother except to say that if can do this because it is a special form as opposed to other forms which evaluate all their parameters. This is glossed over here as well as macros which are apparently similar. This will come up again in chapter 16 it seems.

There are a number of alternatives to if. when and unless are mirror siblings.

when executes its commands if {boolean} is true and, as might be guessed, unless executes its commands if {boolean} is false. These each will take an command list of arbitrary length. Both return nil and do nothing if {boolean} is not the correct value.

Finally there are 2 conditional functions that are fully flexible. I almost said functional but while the prior conditionals have been somewhat less flexible than the conditionals of other languages it's worth noting that they're easy to understand and read, and are largely self documenting. These two, on the other hand, are more like another language's switch/case statement, are complex to read (lots of syntax which, in Lisp, is parentheses and hard for an unpracticed human eye to track) and not very self-obvious. They can be formatted to be easier to read and written to be, or the surrounding code architected to be, easier to grok but there's a limit to how much that can accomplish. The book mentions none of that and perhaps I'm just suffering from a neophyte's inadequacies; it is mentioned that seasoned Lispers prefer cond because of it's generality. I don't know, but without further ado however here is the cond and case functions.

Clearly these two can quickly become hard to read. Nevertheless they're probably called for in some circumstances. cond takes a what is basically a list of when forms. The first matching {boolean} is executed and the remainder ignored. As one might expect the final {boolean} is often a true value to drive default behavior. case is nearly a C style switch statement. It takes a {symbol} which it will compare to the various {value}s defined in its body using (specifically) the eq function (this will have more meaning in a minute) and executes only the matching branch. It isn't stated explicitly but the otherwise branch is default behavior.

There are 2 boolean operator functions of note. and ... and... or. These each take a list of parameters and return a boolean based on the boolean evaluation of those parameters much like you would expect. There is an interesting side effect of the short circuit operation of these functions. Take the following example (ripped straight from the book).

In the above form the 3 parameters are fed to and. You could imagine this being called when an editing program is closed. First the *file-modified* variable is tested and if it's false and immediately returns nil. If it's true then the function (ask-user-about-saving) is tested. Presumably this takes input from the user. If the user inputs a value that is evaluated to true then the (save-file) function is executed. In theory this would return a success/failure variable which would then determine whether and returns nil or true. All of that in one little line. That's some pretty dense semantics. It might be better to use a more verbose if structure if the code needs to be maintained by neophytes since all of the relies on some subtle effects. Personally, I like the density and this case isn't terribly difficult to figure out. Maybe it's just because I grok short circuit evaluation, I dunno.

In a slight tangent the book interjects that one subtlety of the Lisp definition of false is that functions get a freebie return value. Anywhere that a function could return truth or falsehood it would be better to find some more useful value to return than just true; if you're testing whether a variable is defined you might as well return the value (unless it's nil!) since it will be evaluated as true regardless of the actual value. The book uses the member and find-if functions to discuss this but I'm not going to get into them since this is already long and I want to move on to chapter 5.

Finally we come to the equality functions. The book discusses 6 commonly used equality functions. Yes, 6! equal, eql, eq, =, string-equal, and equalp. The rule of thumb is to use eq to compare symbols (it's fast, efficient, and doesn't work well on things that aren't symbols) and to use equal for everything else. I don't have the gumption to dig far into equality comparison right now but will point out that equalp will handle case insensitive string comparisons as well as comparing integers to floating point values.

Friday, June 8, 2012

Land of Lisp Chp3 Summary

In the chapter 2 summary I started digging into the language based on vague remembrances from trying to learn Lisp a few years ago. It didn't work out back then, for various personal and (probably) psychological reasons but we're moving forward this time. Anyway. I might as well have waited (I'm glad I didn't though) because chapter 3 fulfills.

I must begin with the parts I find boring because an understanding of them makes the remainder of the summary more clear and easier to write about. So syntax in Lisp is composed entirely of parentheses. You have a (, a series of symbols, and a ). The () bounds lists and lists compose the semantics of Lisp.

So what kind of data types are recognized by the interpreter? Symbols are composed of alphanumerics and certain symbolic characters ( +,-,=,_,/,*, &etc). I don't know the exhaustive list of allowed characters, that's what google is for. Symbols are case insensitive (though apparently common practice is to avoid capitals).

There are two kinds of numbers, integers and floating points. Lisp handles these pretty much silently, like new interpreted languages, converting ints into floats anytime they're calculated together. However unlike newer languages (that I'm aware of) uneven division of integers does not generate a floating point. (/ 4 6) yields [2/3] not 0.66666666... . Of course [( / 4.0 6)] gets 0.6666667 as one would expect (presumably to the precision defined in code or the default precision of the interpreter). The book also assures me that 2/3 is handled appropriately by the interpreter going forward.

A corollary to the above is that it suggests that one could input rational fractions directly into the interpreter and expect them to be handled properly rather than needing to convert them to irrational numbers first (or have the code do, which will invariably end up creating a float eventually when what you really want is an int, but I digress).

Moving right along, finally we have strings. Quite conventional, they're anything in double quotes and honor the usual escapism with \'s.

An important point is knowing how to tell Lisp when you're entering data instead of code. By default the interpreter treats input as code. Using a single quote you can instead have it treated as data.

This is called quoting, appropriately enough, and causes the interpreter not to evaluate the quoted block. This is largely glossed over here, possibly to be expounded upon later.

Earlier I stated that everything in Lisp is a list. This is only part of the truth. First a little vocabulary correction. I started calling commands like ash and let, and function names keywords. It seems that these are more properly called symbols as discussed above. Groovy. It's just a word, but it should be self-evident that in languages words are of the utmost import. To move on with the point the list is only the second most important structure in Lisp. In fact I think one could say that there are structures in Lisp that are not lists. These are the things that lists are made out of. While it is clearly possible to have a list of lists one must assume that at some point a list must contain something other than another list. Otherwise you might as well say that you have an unending progression of nested boxes each containing yet more boxes. Fascinating mental simulation and yet quite pointless. At some point you reach data which is composed of multiple points which are not themselves a list. This sentence for example is a list of words, and formatting characters. Each word is a list of letters. Each letter is indivisible (semantically, the pixels constructing the letter onscreen have no semantic meaning). Thus the letters in a sentence are the data points.

Ugh. Let me dig myself out of that rabbit hole. I go rather far afield sometimes trying to find and shape a good metaphor. Moving right along. Similarly, each list in Lisp must be composed of something besides lists eventually. That something is the cons. Earlier in chapter 2 I called the second list in a let statement a list of tuples. While this may be strictly accurate my understanding now is that they are handled internally as conses. A cons consists of pointers to precisely two items. I immediately leap ahead and start thinking 'linked list!' which is good, but I have to restrain myself. I'm getting to that. Before I get any further let me elaborate on the command structure. Every command in Lisp follows a specific structure in it's list. A command list is called a form and consists of a special command symbol (generally a builtin or function) followed by a list which will be presented to the special command as parameters. This works the same for builtins and user defined functions.

So the second item in the let syntax is a list of conses to be presented to let as a parameter (yes, singular, it's only one list). Now here's the interesting thing. The the items in a cons can be a pointer to another cons. Here is where linked lists come in. Every list in Lisp is a collection of linked conses.

Now. To create a cons one simply uses the cons command. Brilliant innit?

Don't ask me how to use that syntax to reference an existing cons in an existing list. I haven't got that far yet. So now we have 3 ways to create a list. We can cons it together from constituent parts

We can explicitly declare a list

Or we can imply a list in data mode and let the interpreter sort it out

Is one way better than the other? Hell if I know, but it seems to me that explicitly using list would be less prone to human error than the consing method and less susceptible to interpreter shennanigans than implying one in data mode. But then again I'm a neophyte. What do I know?

There are two primary means of manipulating a list by its conses. Those are car and cdr. car gets the first element. For a variable, the name; for a function, the symbol of the special command. cdr gets the second element.For a variable, the value; for a list the second element of a cons is the pointer to the next cons in the chain so what you get is the original list minus the first element (instant stack behavior). These two can be combined to access arbitrary elements of lists; to parse it you have to read the symbol right to left. For example cadr gets you the first element of the second element of the original list. For example the cadr of ("coffee cup", "mouse", "laptop", "phone") is "mouse". The cddr of it is ("laptop", "phone").

These combinations are implemented as builtins up to 4 layers deep however I suspect how deep they go is at least partly implementation-specific even if that isn't stated explicitly. Nevertheless it's easy enough to define them yourself. cadr is equivalent to saying


Chapter 4 is... you know what? I can't be bothered to manually do a linked list out of these. Just hit the land of lisp tag and be done with it.

Tuesday, June 5, 2012

On a Tuesday morning

I'm behind schedule on Lisp now so I burnt the schedule. I have a partial summary of chapter 3 but it seems at this point I'm going to have to skim back through it again to get the final draft finished. Should have done that this morning but I played file manager with my trio of HDDs instead.

Edit: Pandora is being quite apropo. "Complete the motion if you stumble" ~ Red Hot Chili Peppers, Can't Stop

I'll be glad to trade my cobbled, bunch-of-single-drives configuration for a decent, roomy storage drive. That's delayed so the kids can get tablets, which is wholly worthwhile, but it's still on the horizon I think. My accountant can chime in here if she wants.

Last night we had the youth pastor's family over for dinner. I thought it went well, and the kids both plan to walk down on Father's Day which will be very nice.

Monday, June 4, 2012

Land of Lisp Chp1 Summary

It strikes me that I never formally summarized chatper 1.
It's basically just an overview of the Lisp language as an idea. History, why it's worth understanding, and getting an interpreter installed.

Surely all very useful, but, not terribly meaty. It'd be like summarizing the review papers before taking a test.

Chapter 2 is much more interesting.

I've decided that I can't be bothered to manually do a linked list out of these. Just hit the land of lisp tag and be done with it.

Sunday, June 3, 2012

Land of Lisp Chp2 Summary

Alright. I'm late. Story of my life. Moving right along.
Chapter 1 covered fluffery like history, why learn Lisp, and getting an interpreter set up.
Chapter 2 covered some programming basics.

  • Setting up variables 
    • Global with defparameter, which is probably intended to 'define' the operating 'parameters' of the code set. Whether this should actually be used to store operating variables I'm uncertain, certainly globals are probably better avoided at any rate.
    • Static global with defvar, though I'm sure I'm misunderstanding this one, it was only glossed over.
    • In a local context with let. A more traditional variable. An interesting point is that let literally defines the scope of the variables using the () syntax. In a and b only exist within the {code body} of the outer set of brackets.
setf was glossed over but can, apparently, be used to assign a value to a global defined with defparameter though presumably not defvar, though this isn't explicitly stated (in fact, calling defvar a static may be incorrect, all that is stated explicitly is that it cannot be redefined to a different value using another defvar call whereas defparameter can be).


Then the simple arithmetic shift function which binary shifts {value} by {int}. Binary math is one of the basics I need to work on. Defining ash is simple, grokking it takes some effort.

Finally we have function definitions.

Creates a global (I think?) function. This is the 2nd chapter, things like scope and the subtleties of variable definition aren't being explicitly stated. Anyway. {name} is, clearly, the name you'd use to call this function later. {parameter names} is simply a list of variable names for the function's parameters. {function list} is the code that will be executed. So.

Anytime you call sna it will add foo and bar, the result of which will be implicitly returned to the calling context (either the function call it was used within or to output if it was called directly from the REPL. Which reminds me, the REPL is the basic interface to the Lisp interpreter. It stands for Read Eval Print Loop. It does precisely what it says.


Moving along, there's local function definitions with flet. The syntax is slightly different.

Once again, there's a {name}, {parameter names}, and {function code} however they're enclosed in double ()s. No idea why, yet. That took me a second. The addition of ellipsis indicates that you can define multiple functions for the {code body} in the same way as let. Finally there's the {code body} which contains the code where {name} is in scope.


And the last function definition method covered was labels. labels, apparently, is a window into recursion. It allows functions to be called within other functions defined in the same labels form. I think the book actually has a typo in its example here. First because it won't pass the interpreter and second because the listed example doesn't make sense for Lisp. And the parentheses don't match. Oh, and the proposed output doesn't even make sense.
The book:

That doesn't interpret. It blows chunks because the function 'b' isn't defined. Which makes sense visually. Here's my rewriting which passes the interpreter test:

I laid it out slightly differently too, makes it easier for me to read. To be honest I don't care if it breaks convention (I don't even know what they are yet), I'm not used to reading all those parentheses and I'm not writing code for the perusal of others so I'm going to write it however makes it easiest to read. Moving right along. Here's the generic syntax, assuming I'm right and the book is not:

Condensed like that it's hard to read, but again it's very much the same syntax as flet it just allows each {name} in the function list to reference any other functions in the list. 


Here's an interesting point. LisP is short for List Processor. As the name implies everything in LisP is a list. (I'm pulling this from an aborted attempt to plow through another book on ANSI Common Lisp from a few years ago) Even the functions. The basic syntax is always

where keyword is a builtin command or defined function name, and list is the parameters for the keyword to operate on. Using that nomenclature you can rewrite all of the above. I'm going to make some guesses down here about the underpinnings of the language. I'll probably be wrong, but hey. Grokking it piece by piece.

let takes as parameters a list of tuples for variables and an arbitrary list of additional commands to be parsed. The action that the keyword let performs is basically to replace the occurrences of the keyword with the value each time it sees one of its tuples in the command list.

defun takes a keyword , a list of keywords, and an arbitrary list of commands. The first keyword is taken for a label, or name, or reference, or something. I'm not sure how it's handled or what it's called in the guts of the interpreter. Then you have, basically, which looks a lot like let, doesn't it? I presume the interpreter does something like applying let to each item in {list of keywords} on each function call and then parsing the {list} in that context. flet and labelscan be similarly rewritten by assuming flet to apply defun to each item in {list of functions} which then would apply let to each {list of keywords} within the defuns etc etc ad nauseum. That's why we let the interpreter do it. But in the end it always ends up in a flat list which it processes based on the interpreter's builtins and passes the results back up the stack all the way to, eventually, the REPL. I'm not quite sure how labels works to implement recursion, I assume there's different kinds of internal names? Anyway, that will come later.





I've decided that I can't be bothered to manually do a linked list out of these. Just hit the land of lisp tag and be done with it.

Edit: I went through and crammed all the code bits into gists. It isn't perfect and may not be the best solution, but it'll do.

Saturday, June 2, 2012

Morning coding

This lisp study first thing in the morning might work out alright. We'll see. Just completed chp2 this morning covering some basics. I'll summarize after we get back from the beach this afternoon. That should allow me to implement some of the latest understanding of learning, namely that recovering material after a short break is a highly effective strategy.