<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" 
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:admin="http://webns.net/mvcb/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
	<channel>
<title>Artful code</title><link>http://artfulcode.nfshost.com/index.html</link><description>Latest articles at Artful Code</description><dc:language>en</dc:language><dc:creator>jeffober@gmail.com</dc:creator><dc:rights>Copyright 2007 Jeff Ober</dc:rights><dc:date>2008-01-31T08:06:10-05:00</dc:date><admin:generatorAgent rdf:resource="http://www.realmacsoftware.com/" />
<admin:errorReportsTo rdf:resource="mailto:jeffober@gmail.com" /><sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase>
<lastBuildDate>Thu, 31 Jan 2008 08:06:51 -0500</lastBuildDate><item><title>Moved (again)</title><dc:creator>jeffober@gmail.com</dc:creator><dc:subject>Articles</dc:subject><dc:date>2008-01-31T08:06:10-05:00</dc:date><link>http://artfulcode.nfshost.com/files/da15a64109adbc17d6d4be35f58fc31b-36.php#unique-entry-id-36</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/da15a64109adbc17d6d4be35f58fc31b-36.php#unique-entry-id-36</guid><content:encoded><![CDATA[This website has moved to <a href="http://www.artfulcode.net">ArtfulCode.net</a>.]]></content:encoded></item><item><title>On hiatus</title><dc:creator>jeffober@gmail.com</dc:creator><dc:subject>Articles</dc:subject><dc:date>2008-01-14T13:45:27-05:00</dc:date><link>http://artfulcode.nfshost.com/files/on-hiatus..php#unique-entry-id-35</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/on-hiatus..php#unique-entry-id-35</guid><content:encoded><![CDATA[With the birth of my daughter, I have not had much chance to keep up with Artful Code.  I apologize to those who read regularly, and I will begin posting new articles as soon as possible.]]></content:encoded></item><item><title>Partial Application and Currying</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-12-04T12:33:03-05:00</dc:date><link>http://artfulcode.nfshost.com/files/partial-application-and-currying.html#unique-entry-id-34</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/partial-application-and-currying.html#unique-entry-id-34</guid><content:encoded><![CDATA[Currying, known in Python land as partial application, is a technique in which a function taking multiple arguments composes a function that takes fewer arguments (in most languages, reducing to one, although this is not the case in Python) by partially applying it to given parameters.

...I found a nice little currying function for Javascript here (edit: it was pointed out in a reader's comment (here and at dzone) that this version of curry does not work on previously curried functions; below it is a modified version which will function as expected):

<pre><code><strike>function curry(fn, scope) { var scope = scope || window; var args = []; for (var i=2, len = arguments.length; i < len; ++i) { args.push(arguments[i]); }; return function() {</strike> /* one big problem here is that the following statement is not returning the applied function....  function curry(fn, scope) { var scope = scope || window; var args = []; for (var i = 2; i < arguments.length; i++) { args.push(arguments[i]); } return function() { // this takes care of the arguments problem var fn_args = []; for (var i = 0; i < args.length; i++) { fn_args.push(args[i]); } for (var i = 0; i < arguments.length; i++) { fn_args.push(arguments[i]); } // this takes care of the null return problem return fn.apply(scope, fn_args); }; }</code></pre>

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/partial-application-and-currying.html"; title = "Partial Application and Currying"; summary = "Currying, known in Python land as partial application, is a technique in which a function taking multiple arguments composes a function that takes fewer arguments (in most languages, reducing to one, although this is not the case in Python) by partially applying it to given parameters.]]></content:encoded></item><item><title>Multi-threading in Python</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-11-30T10:02:18-05:00</dc:date><link>http://artfulcode.nfshost.com/files/multi-threading-in-python.html#unique-entry-id-33</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/multi-threading-in-python.html#unique-entry-id-33</guid><content:encoded><![CDATA[def get_file(url): try: f = urllib.urlopen(url) contents = f.read() f.close() return contents except IOError: print "Could not open document: %s" % url</code></pre>

...def run(self): try: f = urllib.urlopen(url) contents = f.read() f.close() return contents except IOError: print "Could not open document: %s" % url</code></pre>

...q = Queue(3) prod_thread = threading.Thread(target=producer, args=(q, files)) cons_thread = threading.Thread(target=consumer, args=(q, len(files)) prod_thread.start() cons_thread.start() prod_thread.join() cons_thread.join()</code></pre>

...q = Queue(3) prod_thread = threading.Thread(target=producer, args=(q, files)) cons_thread = threading.Thread(target=consumer, args=(q, len(files)) prod_thread.start() cons_thread.start() prod_thread.join() cons_thread.join()</code></pre>

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/multi-threading-in-python.html"; title = "Multi-threading in Python"; summary = "Programming with threads is one of the more difficult tasks in programming.]]></content:encoded></item><item><title>Dynamic URLs in Django</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-11-12T15:40:20-05:00</dc:date><link>http://artfulcode.nfshost.com/files/dynamic_urls_in_django.html#unique-entry-id-32</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/dynamic_urls_in_django.html#unique-entry-id-32</guid><content:encoded><![CDATA[The only feature of Code Igniter that I really miss in Django is the ability to add a page without first registering the url, formulating a regular expression to describe the parameters and variations of the view function, and then creating the view and template.

...The url pattern is simple enough: <pre><code>(r'^/path/to/app/root/(?P&lt;view&gt;.+?)/(?:(?P&lt;segments&gt;.+?)/)?$', free_pattern)</code></pre> Placing this at the end of your urlpatterns tuple will allow any undefined urls to go through this as a last-chance catch-all.

...Here is the function: <pre><code>def free_pattern(request, view, segments=""): segments = segments.split(r'/') try: view_fn = getattr(PATH_TO_APP, view) except AttributeError: raise Http404 return view_fn(request, *segments)</code></pre> The function is simple enough.

...If the view is found in the appropriate module (defined using PATH_TO_APP, which should point to whichever application we are talking about), it is run with *segments expanded as its arguments.

...This could easily be expanded to introspect the path to the application, but since Django supports a number of different layouts for applications and projects, that will most likely be very customized to your setup.]]></content:encoded></item><item><title>Extending Python with Pyrex</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-10-23T13:20:11-04:00</dc:date><link>http://artfulcode.nfshost.com/files/extending_python_with_pyrex.html#unique-entry-id-30</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/extending_python_with_pyrex.html#unique-entry-id-30</guid><content:encoded><![CDATA[def count_chars_pyrex(text): chars = CharIterator(file_text) ascii = range(0, 128) counts = [0 for i in ascii] for c in chars: counts[c] += 1 return convert_list(counts)  def count_chars_native(text): ascii = range(0, 128) counts = [0 for i in ascii] for c in text: i = ord(c) counts[i] += 1 return convert_list(counts)  def convert_list(lst): ascii = range(0, 128) counts = {} for i in ascii: char = string_of_int(i) if char in counts.keys(): counts[char] += lst[i] else: counts[char] = lst[i] return counts

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/extending_python_with_pyrex.html"; title = "Extending Python with Pyrex"; summary = "Pyrex is an elegant solution to the problem of extending Python in C.  More so than SWIG, Pyrex is the pythonic solution, allowing the extension to be written in Python and then compiled to C.";]]></content:encoded></item><item><title>Java from a functional perspective</title><dc:creator>jeffober@gmail.com</dc:creator><category>Java</category><dc:date>2007-10-15T11:11:05-04:00</dc:date><link>http://artfulcode.nfshost.com/files/functional_java.html#unique-entry-id-29</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/functional_java.html#unique-entry-id-29</guid><content:encoded><![CDATA[It takes a lot of code to abstract the ability of an IDE to format multiple languages (in particular, the ability to format both C-style languages and Lisp-style languages using the same application primitives presents difficulty).

...It is very helpful to declare local variables based on the pattern of the argument(s) passed to a function, but that would not be useful in Java, since the primary type mechanism in Java is the class rather than the list.

...While this means that the language sometimes suffers from the lack of a particular feature, it also means that there is a guarantee against discovering too late that a feature used in the core of your program will not limit its utility on other operating systems.

...With NetBeans taking care of checking your work for you, I am beginning to suspect that the many buggy Java programs are due to poor programming rather than a problem inherent in Java itself.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/functional_java.html"; title = "Java from a functional perspective"; summary = "A kind look at Java from the perspective of a functional programmer.";]]></content:encoded></item><item><title>Concurrency in newLISP</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-09-18T09:25:15-04:00</dc:date><link>http://artfulcode.nfshost.com/files/concurrency-in-newlisp.html#unique-entry-id-28</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/concurrency-in-newlisp.html#unique-entry-id-28</guid><content:encoded><![CDATA[The first, which we will call spawn (since I like Erlang), will fork a child process that will evaluate an expression, allocate a shared memory address, and create a semaphore to signal the process.  <pre><code>(define-macro (spawn) (letn ((expr (args 0)) (sem (semaphore)) (res (share)) (pid (fork (begin (let ((res-val (eval expr))) (semaphore sem -1) (share res (source 'res-val)) (exit)))))) (list pid sem res)))</code></pre>

...<pre><code>(define (receive proc , res-val serialized-result) (let ((pid (proc 0)) (sem (proc 1)) (res (proc 2))) (semaphore sem 1) (wait-pid pid) (setq serialized-result (share res)) (share nil res) ; release shared memory (semaphore sem 0) ; release semaphore (if (catch (eval-string serialized-result) 'res-val) res-val 'invalid-result)))</code></pre>

...To avoid side effects, we declare res-val locally in our arguments (placing local variables after a comma in a lambda list is a newLISP convention to create local, nil variables; it is no different than declaring them as nil in a let statement or using the function local) and catch the result in it.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/concurrency-in-newlisp.html"; title = "Concurrency in newLISP"; summary = "How to automate semaphores and shared memory to achieve simple concurrency in newLISP.";]]></content:encoded></item><item><title>Functional programming</title><dc:creator>jeffober@gmail.com</dc:creator><category>Functional</category><dc:date>2007-09-10T08:34:22-04:00</dc:date><link>http://artfulcode.nfshost.com/files/functional-programming.html#unique-entry-id-27</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/functional-programming.html#unique-entry-id-27</guid><content:encoded><![CDATA[In this example, $x is a variable, = is an assignment operator (meaning a sort of function that changes the state of the left-hand-side expression, which typically must be a variable of some sort), and ++ is the postfix increment operator (an operator that increases the value of variable by one).

...newLISP: <pre><code>(let ((table "address_book") (fields '("id" "first_name" "last_name" "phone" "email"))) (format "SELECT %s FROM %s" (join (map (fn (field) (format "`%s`.`%s`" table field)) fields) ", ") table))</code></pre>

...PHP: <pre><code>echo "&lt;table&gt;&lt;tr&gt;"; foreach ($fields as $field) { echo "&lt;th&gt;$field&lt;/th&gt;"; } echo "&lt;/tr&gt;"; foreach ($results as $row) { echo "&lt;tr&gt;"; foreach ($row as $value) { echo "&lt;td&gt;{$value}&lt;/td&gt;"; } } echo "&lt;/table&gt;";</pre></code>  newLISP: <pre><code>(let ((row-format (curry format "&lt;tr&gt;%s&lt;/tr&gt;")) (field-format (curry format "&lt;th&gt;%s&lt;/th&gt;")) (value-format (curry format "&lt;td&gt;%s&lt;/td&gt;"))) (println (format "&lt;table&gt;%s%s&lt;/table&gt;" (row-format (join (map field-format fields))) (join (map row-format (map join (map (curry map value-format) results)))))))</pre></code>

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/functional-programming.html"; title = "Functional programming"; summary = "A basic introduction to some of the concepts of functional programming for the imperative/object oriented coder.";]]></content:encoded></item><item><title>Faster string iteration using unpack</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-08-23T12:23:28-04:00</dc:date><link>http://artfulcode.nfshost.com/files/faster-string-iteration-using-unpack.html#unique-entry-id-26</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/faster-string-iteration-using-unpack.html#unique-entry-id-26</guid><content:encoded><![CDATA[Looking at the documentation, we see that "b" is the pattern for an 8-bit, unsigned integer (C represents an ascii character using its ascii code), which is what we wish to extract from the string.

...Note that dup is used to repeat the pattern as many times as is necessary to get all characters of out 'text, using (length text) to determine the number of characters in 'text.

...<pre>(set 'char-list (unpack (dup "b" (length text)) text)) (set 'counts (array 128 (dup 0 128))) (dolist (c char-list) (nth-set (counts c) (+ $0 1)))</pre>

Now we have an array where the index corresponds to an ascii value and the value of the index is the count of characters in 'text.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/faster-string-iteration-using-unpack.html"; title = "Faster string iteration using unpack"; summary = "How to quickly explode a string into a list of its characters' ascii codes.";]]></content:encoded></item><item><title>Why not dynamic scope?</title><dc:creator>jeffober@gmail.com</dc:creator><category>Etc</category><dc:date>2007-08-21T21:06:26-04:00</dc:date><link>http://artfulcode.nfshost.com/files/why-not-dynamic-scope.html#unique-entry-id-25</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/why-not-dynamic-scope.html#unique-entry-id-25</guid><content:encoded><![CDATA[When a side effect is necessary, such as in a function that prints out data, alters or depends on an external variable, or modifies a parameter destructively, it should be well-documented so that a careful programmer will know what to expect.

...Interestingly enough, Scheme, which is lexically scoped, champions this form of side effect free programming, as do most functional languages (although they are often lexically scoped out of necessity).

...These are useful utilities, but I tend to think that dynamic scope is more elegant in that it 1) more expressively reflects the state of the program, and 2) aligns more cleanly with the idea of lambda calculus (arguably the basis of Lisp).

...In large, complex programs, dynamic scoping makes it much more difficult to troubleshoot; lexical scopes allow the programmer to more easily visualize the local variable context when looking at a block of code.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/why-not-dynamic-scope.html"; title = "Why not dynamic scope?"; summary = "A rare argument for dynamic scope.";]]></content:encoded></item><item><title>Writing Python modules in C with SWIG</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-08-14T09:53:13-04:00</dc:date><link>http://artfulcode.nfshost.com/files/writing-python-modules-in-c-with-swig.html#unique-entry-id-24</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/writing-python-modules-in-c-with-swig.html#unique-entry-id-24</guid><content:encoded><![CDATA[Happily, Python's re is UTF-aware and so can make these substitutions for us. However, iteration in Python, especially over a potentially large string, is expensive, and using regular expressions for this sort of thing is not to be thought of.

...So I wrote a simple C module with a function that accepts a string pointer, iterates through each character, incrementing an array (using the int cast of the character as the character's index in the array).

...From there, we can use a simple Python CGI (or FastCGI or mod_python app, depending on what your host supports) that reads in the string from a web form and uses our new library, tally, to count the characters.

...Now I don't have to change the source code at all to use this library in another app. Additionally, I had never used SWIG before and did not want to overcomplicate matters by messing with lower-level stuff, especially since the big performance problem (the string iteration) had been solved, and I now had cycles to spare.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/writing-python-modules-in-c-with-swig.html"; title = "Writing Python modules in C with SWIG"; summary = "Using SWIG to write effortless C modules for Python.";]]></content:encoded></item><item><title>Updating the newLisp MySQL5 Module</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-08-01T15:55:54-04:00</dc:date><link>http://artfulcode.nfshost.com/files/updating-newlisp-mysql.html#unique-entry-id-23</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/updating-newlisp-mysql.html#unique-entry-id-23</guid><content:encoded><![CDATA[The reason that I had worked on it to begin with was to attempt a better MySQL module than the current mysql5.lsp module that comes with the newLisp distribution, but due to time constraints, I have instead written some alterations to the current one that provide many of the same features that I was looking for initially, and fixing a few of the more superficial and crucial problems that I found in the library (in particular, fetch-all's habit of leaving around old result sets without clearing the data by using a context-global variable for storage, rather than a local variable).  New features in this version of the module: <ul> <li>Fixed fetch-all to use a local variable to prevent alteration of future result sets</li> <li>num-fields: returns the number of columns in the result set</li> <li>result-fields: returns a list of columns' field-names for the current result set</li> <li>fetch-table: maps the column field names to the row data</li> <li>add-path: adds a path to an internal list of paths that init will search for the mysql client library</li> <li>Added several default paths:

...(define (keep-type res_ptr field_addr column_num, data) (set 'type_ptr (mysql_fetch_field_direct res_ptr (int column_num))) ; The field type is the 20th field of the MySQL_FIELD structure ; since fields 1-19 are all 4 byte fields we get the enum value ; like so (set 'data (get-int (int (+ type_ptr (* 19 4))))) ; Consult 'enum_field_types' in mysql_com.h for values (if (= data 1) ;; boolean (get-string field_addr) (= data 3) ;; integer (int (get-string field_addr)) (= data 12) ;; datetime (apply date-value (map int (parse (get-string field_addr) "[-: ]" 0))) (= data 4) ;; float (float (get-string field_addr)) ; else (will handle TEXT type 252) (get-string field_addr) ) )  (define (fetch-row) (if MYSQL_RES (set 'rdata (mysql_fetch_row MYSQL_RES)) (set 'rdata 0)) (if (!= rdata 0) (begin (set 'row '()) (dotimes (field (num-fields)) (set 'field_addr (get-int (int (+ rdata (* field 4))))) (if (= field_addr 0) (push nil row -1) ;; what to do when the field contains NULL (push (keep-type MYSQL_RES field_addr field) row -1))) row)))

...lib) (set 'libmysqlclient lib))) (import libmysqlclient "mysql_init") (import libmysqlclient "mysql_real_connect") (import libmysqlclient "mysql_get_host_info") (import libmysqlclient "mysql_real_escape_string") (import libmysqlclient "mysql_query") (import libmysqlclient "mysql_real_query") (import libmysqlclient "mysql_store_result") (import libmysqlclient "mysql_free_result") (import libmysqlclient "mysql_data_seek") (import libmysqlclient "mysql_fetch_row") (import libmysqlclient "mysql_close") (import libmysqlclient "mysql_fetch_field_direct") (import libmysqlclient "mysql_insert_id") (import libmysqlclient "mysql_num_fields") (import libmysqlclient "mysql_fetch_field") ;; Perform previous definition's actions (set 'MYSQL (mysql_init 0)) (if (= MYSQL 0) (set 'MYSQL nil)) (not (= MYSQL nil)))]]></content:encoded></item><item><title>Using C Libraries in newLisp Part 1</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-07-14T10:43:37-04:00</dc:date><link>http://artfulcode.nfshost.com/files/using-c-libraries-in-newlisp-part-1.html#unique-entry-id-22</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/using-c-libraries-in-newlisp-part-1.html#unique-entry-id-22</guid><content:encoded><![CDATA[The past couple of articles have been tutorials on how to use CFFI to access functions from C libraries in Lisp....  As newLisp is an entirely interpreted language, this built in functionality allows very easy extension of the language using much more low level and efficient libraries.

...From the <a href="http://dev.mysql.com/doc/refman/5.0/en/c.html" rel="self">MySQL C API docs</a>, we know that mysql_init takes a pointer as a parameter and returns a pointer to a MYSQL type struct.

...<pre>MYSQL *mysql_real_connect(MYSQL *mysql, const char *host,<br /> const char *user, const char *passwd, const char *db, unsigned int port, <br /> const char *unix_socket, unsigned long client_flag)</pre>

...It then calls the function and verifies evaluates to true or nil, depending on whether or not the function returned 0, which is the C NULL.]]></content:encoded></item><item><title>Wrapping a C Library in Lisp Part 2</title><dc:creator>jeffober@gmail.com</dc:creator><category>Lisp</category><dc:date>2007-07-03T19:53:49-04:00</dc:date><link>http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-2.html#unique-entry-id-21</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-2.html#unique-entry-id-21</guid><content:encoded><![CDATA[Once the library has been <a href="/files/wrapping-a-c-library-in-lisp-part-1.html">defined and loaded</a> into the Lisp image, work can begin on defining C routines in Lisp.

...Although we can pass an already existing MYSQL object pointer (that's the second part), generally we will just use this function to create the internal struct needed to run the program.

...The second part, MYSQL *mysql, states this- namely, that a pointer (named mysql, and we know it's a pointer because it's labelled with an asterisk- *mysql) will be returned.

...Now, we can simply run (mysql-init) and we will have the symbol *mysql* pointing to the returned pointer or nil in the event of a failure.

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-2.html"; title = "Wrapping a C Library in Lisp Part 2"; summary = "How to use CFFI to import C libraries in Lisp";]]></content:encoded></item><item><title>Wrapping a C Library in Lisp Part 1</title><dc:creator>jeffober@gmail.com</dc:creator><category>Lisp</category><dc:date>2007-07-02T14:06:57-04:00</dc:date><link>http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-1.html#unique-entry-id-20</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-1.html#unique-entry-id-20</guid><content:encoded><![CDATA[CLSQL is a nice solution, but it does not get along well on OSX, my development OS, or with CLISP, which is the primary lisp dialect I have available on my host.

...It has a fairly simple, intuitive syntax for making C routines available to lisp (as a side note, I have not encountered anything as easy as newLisp's C library importer, although this is made easier in that newLisp is implemented in C).

...Since I happen to know that CFFI does find the library path even when explicitly specified, we can conveniently specify a list of full paths to try for each OS.

...This will return a pointer to a foreign address (for the C-challenged, a pointer is a variable to points to a value's address in memory; it is used to access a value by reference, rather than by value) or, in the event that it did not work, it will throw up an error....  <script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/wrapping-a-c-library-in-lisp-part-1.html"; title = "Wrapping a C Library in Lisp Part 1"; summary = "How to use CFFI to import C libraries in Lisp";]]></content:encoded></item><item><title>Nested contexts in newLisp</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-06-21T16:37:39-04:00</dc:date><link>http://artfulcode.nfshost.com/files/nested-contexts-in-newlisp.html#unique-entry-id-16</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/nested-contexts-in-newlisp.html#unique-entry-id-16</guid><content:encoded><![CDATA[However, since they create efficient hashes that can be used for many of the same purposes as objects (such as data modeling), it would be handy if there were a way to create contexts inside of other contexts.

Since we can store a symbol in a context, we can simply point a symbol to one context, then assign that symbol to another context, thus simulating a nested context.  <pre>(context 'profile "full-name" "Some Body") (context 'profile "email" "somebody@somewhere.com") (context 'account "username" "somebody") (context 'account "password" "secret") (context 'account "profile" 'profile)</pre>

...tree) nil) ((>= (length tree) 2) (if (> (length tree) 2) (@ (cons (context (tree 0) (name (tree 1))) (2 tree))) (context (tree 0) (name (tree 1)))))))</pre>

...<script type="text/javascript"> url = "http://artfulcode.nfshost.com/files/nested-contexts-in-newlisp.html"; title = "Nested contexts in newLisp"; summary = "How to simulate nested contexts using a simple recursive function in newLisp.";]]></content:encoded></item><item><title>Validating parameter format</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-06-19T08:58:02-04:00</dc:date><link>http://artfulcode.nfshost.com/files/validating-parameter-format.html#unique-entry-id-12</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/validating-parameter-format.html#unique-entry-id-12</guid><content:encoded><![CDATA[However, if you are developing a library or module that other projects may mix into their own code, it is useful to give helpful errors when a function receives incorrect input.  Especially if your documentation is lax (which we know it never is), throwing usable errors when a function is misused will make the lives of developers using your code that much easier.

...We will want to accept a predicate that will validate the value, which we will also need to accept, as well as the name of the calling function in order to produce a useful error message.

...Since macros do not evaluate their parameters, if a symbol is passed to a macro that has the same name as the macro's parameter, the symbol's meaning will be overridden in the local scope.

...If we are negating the predicate, we also need to strip the exclamation point off of the symbol in order to evaluate it later.]]></content:encoded></item><item><title>Simple error handling in newLisp</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-06-12T19:51:40-04:00</dc:date><link>http://artfulcode.nfshost.com/files/simple-error-handling-in-newlisp.html#unique-entry-id-11</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/simple-error-handling-in-newlisp.html#unique-entry-id-11</guid><content:encoded><![CDATA[As my software begins to mature and I add more sophisticated error handling, I find that newLisp's simple functions result in cleaner, more expressive code.

When I write Python or PHP, I often find myself spending as much time writing complicated chains of exception handling code, trying to anticipate all possible types of errors ahead of time....  In reality, the vast majority of errors that can happen are due to programmer error, whether it be a forgotten semi-colon (in the case of PHP), or an unexpected input type from a form.  What is more important than handling every type of error is that the problem can be quickly defined and located so that the end user does not experience an excessive outage.

...<pre>(if (catch (error-prone) 'caught) (println "We won't ever get here, because error-prone always throws an error") (cond ((some condition) (some response)) ((some other condition) (some other response)) (true (catch-all response for unhandled errors))))</pre>]]></content:encoded></item><item><title>Avoiding excess redundancy</title><dc:creator>jeffober@gmail.com</dc:creator><category>OOP</category><dc:date>2007-06-08T08:11:04-04:00</dc:date><link>http://artfulcode.nfshost.com/files/avoiding-excess-redundancy.html#unique-entry-id-10</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/avoiding-excess-redundancy.html#unique-entry-id-10</guid><content:encoded><![CDATA[The context used is that of programming a MUD (with which I am just as guilty of wasting my teen years as the author)....  The author shows how the methods for equipping an item can be stored in the player object or the item object, and that the latter (an example of using antiobjects) was more efficient.

...It is not the person that determines how the item is used, but the item itself that describes its use (in the context of the game).

...But in the context of the program, that would be ridiculous and would require a heck of a lot of extra coding work, adding an enormous amount of complexity to the program.

...And, because this version does not require the replication of many very similar objects, we are not wasting memory and avoiding a lot of introspecting code to keeps everything aligned.]]></content:encoded></item><item><title>Evolving lisp</title><dc:creator>jeffober@gmail.com</dc:creator><category>Lisp</category><dc:date>2007-06-07T20:58:48-04:00</dc:date><link>http://artfulcode.nfshost.com/files/evolving-lisp.html#unique-entry-id-8</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/evolving-lisp.html#unique-entry-id-8</guid><content:encoded><![CDATA[Paul Graham notes that, "A popular recipe for new programming languages in the past 20 years has been to take the C model of computing and add to it, piecemeal, parts taken from the Lisp model, like runtime typing and garbage collection."

...Python may be the most lispy, but there is also Ruby, which conceptually borrows heavily from languages like lisp and Smalltalk.

...newLisp, a dialect of lisp that uses s-expressions in a high level, interpreted language, has borrowed from imperative languages, and has done an excellent job of maintaining its lispy character despite it.

...Common Lisp's LOOP is very powerful but not very idiomatic of lisp and not very elegant to use (in fact, many of those involved in the original development of the language did not like LOOP, feeling that it was not lispy enough).

...Lisp was built to evolve, so it's a shame that so few of the people who continue to plough ahead in the language want it to.]]></content:encoded></item><item><title>Art is rough</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-06-01T16:57:44-04:00</dc:date><link>http://artfulcode.nfshost.com/files/art-is-rough.html#unique-entry-id-7</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/art-is-rough.html#unique-entry-id-7</guid><content:encoded><![CDATA[The idea is to check for equality against the 30k strings in list one on each of the cells in list two, then replace that with a predefined string if equality is met.

...Naturally, the forum user used a recursive function, ref-all, which provides an index of placement of an atom in a list (i.e. (ref-all "baz" '("foo" "bar" "baz" "bat")) => 2).  Then he mapped a lambda to list one that ref-all'd the item from list one in list two, replacing it with "FOO".

The problem was that this was using a recursive function on a huge list over and over again, and newLisp is not optimized for large lists of strings as it is.  It turns out that I was able to speed it up by using one of newLisp's iterators, dolist, which simply iterates over a list.]]></content:encoded></item><item><title>Why Ruby is an acceptable PERL</title><dc:creator>jeffober@gmail.com</dc:creator><category>Perl</category><dc:date>2007-05-31T20:56:14-04:00</dc:date><link>http://artfulcode.nfshost.com/files/why-ruby-is-an-acceptable-perl.html#unique-entry-id-6</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/why-ruby-is-an-acceptable-perl.html#unique-entry-id-6</guid><content:encoded><![CDATA[Everyone has read <a href="http://www.randomhacks.net/articles/2005/12/03/why-ruby-is-an-acceptable-lisp">this article</a>.

...However, few Rubyists like to compare their language with Perl because Ruby is religiously object oriented, and Perl is more of an example on how not to implement OOP.

...It inherits a lot of features from languages like Smalltalk and lisp, but if you look at a large Ruby program, you begin to see how Perl-like it is.

...As with Perl, syntactic freedom means that the neatness of code is often a product of the mood of the programmer or the deadline.  Coming back to a program after six months can mean hours of analyzing code, trying to figure out what on earth you were thinking when you wrote that.]]></content:encoded></item><item><title>newLisp in context</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-05-25T19:52:52-04:00</dc:date><link>http://artfulcode.nfshost.com/files/newlisp-in-context.html#unique-entry-id-5</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/newlisp-in-context.html#unique-entry-id-5</guid><content:encoded><![CDATA[However, if one prototype has an object in it that must be prototyped from another context, we run up against the nested contexts wall.

...If I create a new model using the table prototype, I now cannot access the internals of the fields in the model - (model:field:foo) does not work.

...Now, I still want to fence this list off so that it can be safely extended as well as passed as an argument to other functions (such as a function that writes sql customized for the table).

...If I want, I can create a generic 'model context to prototype my other tables from which has certain functionality already in it....  <pre>(context 'addressdb) (set 'model '("address" (relationship (type "many-to-one") (table "company") (local-key "company_id") (foreign-key "id")) (fields (("id" (type "int(11)") (key true) (uniq true) (auto true)) ("name" (type "varchar(255)") (uniq true)) ("email" (type "varchar(255)") (uniq true) (default "someone@somewhere.com")) ("company" (type "int(11)")))))) (context 'MAIN)</pre>]]></content:encoded></item><item><title>Macros</title><dc:creator>jeffober@gmail.com</dc:creator><category>Lisp</category><dc:date>2007-05-23T20:30:56-04:00</dc:date><link>http://artfulcode.nfshost.com/files/macros.html#unique-entry-id-4</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/macros.html#unique-entry-id-4</guid><content:encoded><![CDATA[<pre>(define-macro (each object do iter) (set 'iter (trim (string iter) "|")) (dolist (obj (eval object)) (eval (set (sym (eval iter)) obj)) (doargs (a) (unless (= a 'end) (eval a)))))</pre>

...Next, we use the doargs function to iterate over the remaining arguments (in newLisp, all arguments not specified in the function definition are available through the command args, and are iterable using doargs).

...Careful readers will note that if there are commands after 'end, they will be executed for a given value of x as well, but hey, it's a blog entry, and we aren't writing a Ruby interpreter :)....  <pre>(each '("one" "two" "three") do |x| (println "I can count to " x) end)</pre>

...<script type="text/javascript"> digg_url = 'http://artfulcode.nfshost.com/files/macros.html'; digg_title = 'Macros'; digg_bodytext = 'Macros are a big stumbling block for many beginning lispers.]]></content:encoded></item><item><title>Utilizing PHP&#x27;s strengths</title><dc:creator>jeffober@gmail.com</dc:creator><category>PHP</category><dc:date>2007-05-21T18:29:35-04:00</dc:date><link>http://artfulcode.nfshost.com/files/utilizing-phps-strengths.html#unique-entry-id-3</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/utilizing-phps-strengths.html#unique-entry-id-3</guid><content:encoded><![CDATA[On the other hand, there are also excellent frameworks, like <a href="http://www.codeigniter.com">Code Igniter</a>, which embrace this (by using PHP objects as scoping mechanisms for function libraries).

...If you wish to expand the program in the future, it takes a lot more work than if the program had been written using OO syntax from the ground up.

...There is a fairly comprehensive set of functions for dealing with arrays as well (at least, comprehensive when not comparing it to Lisp), and a superb iterator for them as well (foreach).

...PHP arrays are much more helpful than classes if you consider PHP in the context of a templating system, rather than an OO language.

<script type="text/javascript"> digg_url = 'http://artfulcode.nfshost.com/files/utilizing-phps-strengths.html'; digg_title = "Utilizing PHP's strengths" ; digg_bodytext = "PHP appears to be migrating toward becoming a sort of cross between Perl and Java.]]></content:encoded></item><item><title>Contextual programming</title><dc:creator>jeffober@gmail.com</dc:creator><category>newLISP</category><dc:date>2007-05-15T16:25:53-04:00</dc:date><link>http://artfulcode.nfshost.com/files/contextual-programming.html#unique-entry-id-2</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/contextual-programming.html#unique-entry-id-2</guid><content:encoded><![CDATA[In many languages, these are called shared libraries: smaller chunks of code that can be reused as needed throughout this and other programs.

In many languages, such as PHP, evaluating the contents of another file necessarily means that its code is run in the current namespace.

...newLisp has a similar concept, but slightly lower level, and somewhat more limited (in that all namespaces are children of the MAIN namespace, and cannot be nested, as in Python).

...In newLisp, 'foo still evaluates to "bar", and 'SOME-CONTEXT:foo evaluates to "baz."

...It's complete lack of programmer-controlled namespaces forces misuse of other parts of the language and encourages bad coding - for which I am just as guilty as anyone.]]></content:encoded></item><item><title>Sequential permutations in Python</title><dc:creator>jeffober@gmail.com</dc:creator><category>Python</category><dc:date>2007-05-14T20:03:24-04:00</dc:date><link>http://artfulcode.nfshost.com/files/sequential-permutations-in-python.html#unique-entry-id-1</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/sequential-permutations-in-python.html#unique-entry-id-1</guid><content:encoded><![CDATA[<pre>wine = ["white", "red", "mad dog 20/20"] first_course = ["salad", "soup"] second_course = ["steak", "chicken"] desert = ["pie", "cake"]</pre>

...""" perms = [] for x in args[0]: for y in args[1]: if isinstance(x, list): z = x[:] z.append(y) perms.append(z) else: perms.append([x, y]) if len(args) > 2: perms = sequence_permutations(perms, *args[2:]) return perms</pre>

......which would create an infinite loop: since we are iterating over y for each element in x, if we add y to the end of x before we terminate the iterations, we end up exponentially increasing the length of x by the length of y on each iteration....  <pre>print "Running sequence_permutations on your dinner:" wine = ["white", "red", "mad dog 20/20"] first_course = ["salad", "soup"] second_course = ["steak", "chicken"] desert = ["pie", "cake", None] for pattern in sequence_permutations(wine, \ first_course, second_course, desert): print pattern</pre>...  <pre>Running sequence_permutations on your dinner: ['white', 'salad', 'steak', 'pie'] ['white', 'salad', 'steak', 'cake'] ['white', 'salad', 'steak', None] ['white', 'salad', 'chicken', 'pie'] ['white', 'salad', 'chicken', 'cake'] ['white', 'salad', 'chicken', None] ['white', 'soup', 'steak', 'pie'] ['white', 'soup', 'steak', 'cake'] ['white', 'soup', 'steak', None] ['white', 'soup', 'chicken', 'pie'] ['white', 'soup', 'chicken', 'cake'] ['white', 'soup', 'chicken', None] ['red', 'salad', 'steak', 'pie'] ['red', 'salad', 'steak', 'cake'] ['red', 'salad', 'steak', None] ['red', 'salad', 'chicken', 'pie'] ['red', 'salad', 'chicken', 'cake'] ['red', 'salad', 'chicken', None] ['red', 'soup', 'steak', 'pie'] ['red', 'soup', 'steak', 'cake'] ['red', 'soup', 'steak', None] ['red', 'soup', 'chicken', 'pie'] ['red', 'soup', 'chicken', 'cake'] ['red', 'soup', 'chicken', None] ['mad dog 20/20', 'salad', 'steak', 'pie'] ['mad dog 20/20', 'salad', 'steak', 'cake'] ['mad dog 20/20', 'salad', 'steak', None] ['mad dog 20/20', 'salad', 'chicken', 'pie'] ['mad dog 20/20', 'salad', 'chicken', 'cake'] ['mad dog 20/20', 'salad', 'chicken', None] ['mad dog 20/20', 'soup', 'steak', 'pie'] ['mad dog 20/20', 'soup', 'steak', 'cake'] ['mad dog 20/20', 'soup', 'steak', None] ['mad dog 20/20', 'soup', 'chicken', 'pie'] ['mad dog 20/20', 'soup', 'chicken', 'cake'] ['mad dog 20/20', 'soup', 'chicken', None]</pre>]]></content:encoded></item><item><title>Lisp: where to start</title><dc:creator>jeffober@gmail.com</dc:creator><category>Lisp</category><dc:date>2007-05-13T13:06:45-04:00</dc:date><link>http://artfulcode.nfshost.com/files/lisp-where-to-start.html#unique-entry-id-0</link><guid isPermaLink="true">http://artfulcode.nfshost.com/files/lisp-where-to-start.html#unique-entry-id-0</guid><content:encoded><![CDATA[After a few years, new features were needed, and by this time, there were already several groups that had written interpreters for the language (lisp is both an interpreted language, like Perl, and a compiled language).

...I originally chose Gnu clisp because it had built in regex functions, whereas many other lisps require that you install a 3rd party library to support regex (and installing 3rd party libraries is a semester-long course in itself).

...I found the online book, <a href="http://www.gigamonkeys.com/book/">Practical Common Lisp</a>, which was helpful, but still a little above my head in some areas.

...The best instruction I found was a book called, <a href="http://www.amazon.com/Common-Lisp-Introduction-Symbolic-Computation/dp/0805304924">Common Lisp: A Gentle Introduction to Symbolic Computation</a>.

...Even if, as with me, you decide to stick with newLisp over other lisps, <a href="http://www.amazon.com/Common-Lisp-Introduction-Symbolic-Computation/dp/0805304924">A Gentle Introduction</a> will still benefit you immensely (even if you don't stick with lisp at all, the book will make you a better programmer).]]></content:encoded></item></channel>
</rss>