<rss version="2.0">
    <channel>
        <title>Copper Thoughts</title>
        <description>Just my place on the internet.</description>
        <link>http://www.copperthoughts.com</link>
        
        <item>
          <title>Too Much Abstraction</title>
          <description>&lt;h2&gt;Object Oriented &amp; Duck Typed&lt;/h2&gt;

&lt;p&gt;If you're not familiar with &lt;a href="http://www.python.org/"&gt;Python&lt;/a&gt;, you owe yourself a few minutes to check it out. It's a beautiful language that lets you get stuff done quickly, with little ceremony. &lt;/p&gt;

&lt;p&gt;That being said, I just can't understand why one would want to write object-oriented code in the language, even given that it really pushes you to write in the OO-style. The primary reasons for writing classes (the poor man's types) is so that you can abstract away a a piece of information, or create a new data type. &lt;/p&gt;

&lt;p&gt;The latter use makes sense, though most of the structures you'd want to use in Python are there, and the ones that aren't are generally better implemented in C. The former use mostly results in boilerplate code. You don't get the beautiful code that results from having static types; no, the language is duck-typed. You have no safety, and no gentle enforcement. Then you have the normal sins of OO: you have your getters, you have your setters, and then you have some domain-specific query and processing methods. In this case, your domain is your class. And what a sad, small domain that is. &lt;/p&gt;

&lt;p&gt;A slightly more appealing option is to inherit from core data structures like &lt;code&gt;UserDict&lt;/code&gt;. But you're still writing more code than you need to be. &lt;/p&gt;

&lt;p&gt;Instead, use the core data structures. &lt;/p&gt;

&lt;hr /&gt;

&lt;h2&gt;Data as Data&lt;/h2&gt;

&lt;p&gt;I recently found myself need to convert from X arbitrary unit to Y arbitrary unit (and so forth) defined by a text file of equalities. A sample: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;4 foo = bar
bar = 3 baz
baz = 2 nar
quark = 7 cthulu
foo = f
bar = b
f = 15 hur
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The idea was to allow me to convert any arbitrary amount of one unit to another, even if it meant many conversions in between. Say, for instance, that I wanted to see how many nars 27 foos was. You could eye the relatively simple list above and see that you'd need to follow the unit path of foo &gt; bar &gt; baz &gt; nar, and apply scalar transformations to the original amount along the way. The transformation looks like this: &lt;code&gt;27 foo &amp;gt; 6.75 bar &amp;gt; 20.25 baz &amp;gt; 40.5 nar&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;But how to represent that in Python? A directed, weighted graph seemed like the best choice to me, so that's what I implemented. The direction indicated the direction of the conversion, with the weight being the scalar by which the units differ by.&lt;/p&gt;

&lt;p&gt;A graph is a set of two sets. The first is a set of nodes, the second is a set of edges. I decided to use a tuple of &lt;code&gt;sets&lt;/code&gt;, one of nodes and one of edges. Nodes are strings representing the units (e.g. foo, bar), and edges are tuples of edges and the conversion weight (i.e. &lt;code&gt;(foo, bar, 1/4)&lt;/code&gt;). Here's how I wrote that in my code: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;"""
graph = (set(node), set(edge))
node = String
edge = (node[origin], node[dest], Fraction(C))
       where C is the fractional conversion factor between node[origin] and 
       node[dest]
"""
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that it's a comment. Every method I need to access and manipulate my data is already there, and everyone who might read my code is familiar with them. I could provide a simple interface if I wanted (e.g. nodes() or edges()), but that would be a little superfluous. Alternatively, this is how I could have described by structure if I had been writing OO code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Graph(Object):
    def __init__(self):
    self.nodes = set()
    self.edges = set()

def nodes(self):
    return self.nodes

def edges(self):
    return self.edges

def addEdge(self, src, dst, c):
    self.edges.add(src, dst, c)

def addNode(self, node):
    self.nodes.add(node)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which appears to be the same thing to me, though obfuscated and verbose, not to mention a bit slower. &lt;/p&gt;

&lt;h2&gt;Hedging&lt;/h2&gt;

&lt;p&gt;Maybe I'm way off the mark here, and the increasing amount of functional programming I have been exposed to has tainted my otherwise pristine intellect. But why hide the data structures behind your datastructure any more than necessary? And in this case, the obfuscation only serves to name the actions being carried out in the context it takes place. &lt;/p&gt;

&lt;p&gt;It's important to note, lest a strawman be made, that this post isn't meant to disparage the abstractions that classes, types, and interfaces provide a programmer. Nor should it apply in the case of an API, where an interface should be specific and clear. &lt;/p&gt;

&lt;p&gt;Instead, I find myself struggling and questioning the need for what I perceive to be ineffectual abstractions. I suppose much of depends on just how much power you're comfortable giving yourself and whoever may use your code, and how much you need to hide in order to keep the code grokable. &lt;/p&gt;
</description>
          <link>http://copperthoughts.com/p/ducks-and-classes-python/</link>
          <pubDate>2011-07-02T05:36</pubDate>
        </item><item>
          <title>Clojure Atlas</title>
          <description>&lt;p&gt;Though I know I'm late to the party, I've been enjoying poking around &lt;a href="http://cemerick.com/"&gt;Chas Emerick's&lt;/a&gt; newest project, &lt;a href="http://clojureatlas.com"&gt;Clojure Atlas&lt;/a&gt;. It's particularly pleasant to use it in conjunction with the &lt;a href="https://github.com/clojure/clojure"&gt;Github page for Clojure&lt;/a&gt;, move to the relevant .clj and browse around it with the Atlas as accompaniment.&lt;/p&gt;

&lt;p&gt;The Atlas is essentially a live graph connecting functions, macros, "Classes", reader syntax and just about everything else you can think of. A single click brings up the source code, as well as the documentation. My one complaint is that the graph takes too long to &lt;em&gt;stop moving&lt;/em&gt;, making it difficult to quickly navigate: according to his Twitter (and my memory), this is something he's working on. My one wish for the product: integration with &lt;a href="http://clojuredocs.org/"&gt;ClojureDocs&lt;/a&gt;, a great resource for burgeoning Clojurists and a way to make Clojure Atlas more accesible to those who are newer to the language, as well as make it more of an encyclopedia. &lt;/p&gt;

&lt;p&gt;&lt;img src="/p/clojure-atlas/clojure-atlas-screenshot.png" alt="example clojure atlas screenshot" width="636" height="512" /&gt;&lt;/p&gt;

&lt;p&gt;It costs $40 if you buy the Atlas for Clojure 1.2 and 1.3 (coming soon), or just $25 if you'd like to buy the 1.2 version. It is definitely worth a look.&lt;/p&gt;
</description>
          <link>http://copperthoughts.com/p/clojure-atlas/</link>
          <pubDate>2011-05-30T06:00</pubDate>
        </item><item>
          <title>Lovely Pianobar</title>
          <description>&lt;p&gt;If you love using Pandora, but really wish they had a command-line (or at least non-Flash) version of the desktop application, this post will make your day. An absolutely wonderful CLI utility called &lt;a href="https://github.com/PromyLOPh/pianobar"&gt;pianobar&lt;/a&gt; solves this problem for you, and a few more you didn't know you had. Something to note: there are no advertisements when using pianobar; this may be violating Pandora's terms of service. Because I think Pandora is supplying a great service, I pay for the $3/month Pandora+ membership and would not be hearing advertisements anyway: if this method seems like a great way to listen to music I'd recommend you pay the $36 too.&lt;/p&gt;

&lt;p&gt;This tutorial will only cover setting up this environment on a Mac, though if you're running Linux you should be able to do much of the same using a few different applications in some cases.&lt;/p&gt;

&lt;h2&gt;What You'll Need&lt;/h2&gt;

&lt;p&gt;With that said, you can build pianobar from source, or use a package manager like &lt;a href="http://mxcl.github.com/homebrew/"&gt;brew&lt;/a&gt; to install it. Occasionally you need to update pianobar in order to get the newest auth keys. This should not be the difficult step.&lt;/p&gt;

&lt;p&gt;You'll also want to install &lt;a href="http://www.alfredapp.com/"&gt;Alfred&lt;/a&gt; (Alfred deserves a whole post to itself) to get this to work, though you could accomplish similar results with KeyboardMaestro or another application launcher like LaunchBar. In order to do this using Alfred, you'll need to buy the powerpack (basically, an upgrade) for around $20. Any way you have of executing scripts via keyboard shortcut will work as well, as will your command-line itself, though. Alfred is definitely worth twenty dollars.&lt;/p&gt;

&lt;p&gt;Finally, you will need &lt;a href="http://growl.info/"&gt;Growl&lt;/a&gt; if you don't already have it, and its CLI utility &lt;a href="http://growl.info/extras.php#growlnotify"&gt;&lt;code&gt;growlnotify&lt;/code&gt;&lt;/a&gt;. If you're opposed to Growl for whatever reason, you don't need it, but it's a nice method of visual feedback.&lt;/p&gt;

&lt;p&gt;I'm going to assume you already use a terminal multiplexor like &lt;code&gt;tmux&lt;/code&gt; or &lt;code&gt;screen&lt;/code&gt;, but if you don't you owe it to yourself to &lt;a href="http://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/"&gt;look into it&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;The Execution&lt;/h2&gt;

&lt;p&gt;If you don't already have one, make a &lt;code&gt;.config/&lt;/code&gt; directory in your home folder and add a &lt;code&gt;pianobar/&lt;/code&gt; directory there as well. Here you'll make a file called &lt;code&gt;config&lt;/code&gt; and write the following in it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user = username@email.com
password = plaintext_password
event_command = /Users/username/.config/pianobar/event-cmd
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Setting your username and password here allows you to start up pianobar and immediately begin listening: it's no fun to have to type your username and p/w in every time (though if you're using tmux/screen you should rarely have to anyway). &lt;code&gt;event_command&lt;/code&gt; lets you designate an executable that will accepts output from pianobar on every event (e.g. starting a new song, hating a song, explaining a song).&lt;/p&gt;

&lt;p&gt;In that file, at &lt;code&gt;/Users/username/.config/pianobar/event-cmd&lt;/code&gt; put &lt;a href="http://www.copperthoughts.com/p/lovely-pianobar/event-cmd"&gt;this&lt;/a&gt; shell script. In short, it parses the output from pianobar sent with every event and, depending on what event is occurring, sends a certain message to Growl.&lt;/p&gt;

&lt;p&gt;In the same directory put an icon you'd like to use, and call it &lt;code&gt;icon.png&lt;/code&gt;. I used &lt;a href="http://www.iconfinder.com/icondetails/42087/64/music_icon"&gt;this simple pixel eighth note&lt;/a&gt; for my icon. It's also possible to specify different icons for different events, as you can see in the shell script.&lt;/p&gt;

&lt;p&gt;Next you'll need to create a FIFO named "ctl" (with &lt;code&gt;mkfifo&lt;/code&gt;) in the same directory. You can send commands to this file and pianobar will respond to them appropriately. Now is probably a good time to start up pianobar in a &lt;code&gt;tmux&lt;/code&gt; session, too. Make sure everything is working so far.&lt;/p&gt;

&lt;p&gt;Finally, we get to tie this all together:&lt;/p&gt;

&lt;p&gt;&lt;img src="/p/lovely-pianobar/alfred-pianobar.png" alt="alfred setup screenshot" width="662" height="512" /&gt;&lt;/p&gt;

&lt;p&gt;Here you can see my current (rapidly growing) list of shell commands Alfred handles for me. More pertinent are the "p" and "pp" commands. The former runs: &lt;code&gt;echo "{query}" &amp;gt; ~/.config/pianobar/ctl&lt;/code&gt;, while the second just toggles play by passing the FIFO "p". In this way, I can open Alfred with &lt;code&gt;CMD+SPACE&lt;/code&gt;,p type "p" and a space, then pass any command to pianobar from there. Most often I send "n" for "next song" or "e" for "explain", which displays the title, artist and album of the song via Growl. If I wanted to, I could bind any function keys I'd like to these commands as well, but typing 3 characters works fine for me. &lt;/p&gt;

&lt;p&gt;So I have a lightweight, easily controlled music setup. If you're cheap, the cost is free. If you'd like to support Pandora as well as get a fantastically useful application, that'll be $46. &lt;/p&gt;

&lt;p&gt;If you'd like to expand more on this setup, be sure to read the pianobar man pages, which are very helpful; you can customize the keys used to control pianobar, manage even more events and more. &lt;/p&gt;
</description>
          <link>http://copperthoughts.com/p/lovely-pianobar/</link>
          <pubDate>2011-05-29T06:18</pubDate>
        </item><item>
          <title>The Ins and Outs of Clojure: Part One</title>
          <description>&lt;p&gt;&lt;small&gt;written about Clojure 1.2&lt;/small&gt;&lt;/p&gt;

&lt;p&gt;It is a truth universally acknowledged, that a programmer using Clojure will want to perform IO. Let me help you out (put). &lt;/p&gt;

&lt;p&gt;I'll go over some of the basics of IO, focusing on what you can use Clojure to do directly. I'll move on after the basic introduction, to some of the more interesting and generally useful classes that Java offers, giving a little context for each.&lt;/p&gt;

&lt;h2&gt;In&lt;/h2&gt;

&lt;p&gt;Reading files in is generally one of the first things I want to do when playing with a new language, so I'll start there. Before I get started though, I should mentioned that in Clojure, strings are always encoded using UTF-16. Generally this saves time and worry, but it's something to keep in mind should you run into problems on the encoding front.&lt;/p&gt;

&lt;h4&gt;slurp&lt;/h4&gt;

&lt;p&gt;Clojure comes with a handy little function called &lt;a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/splurp"&gt;&lt;code&gt;slurp&lt;/code&gt;&lt;/a&gt; that takes in a string representing a filename (or, really, pretty much anything; a File, a stream, a byte array, URL, etc) and returns a string containing the contents of your file. It's pretty handy if you just need to get some information from a file that's relatively small, and you'll be parsing it yourself. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(slurp "/Users/ihodes/Desktop/afile.txt")
=&amp;gt; "A little bit\nof information here."
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A nice thing about &lt;code&gt;slurp&lt;/code&gt; is that you can easily build up file paths with &lt;code&gt;str&lt;/code&gt;. For example, say you want to output to a file based on information you find at runtime:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(slurp (str "/Users/" username "/Desktop/" filename))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But &lt;code&gt;slurp&lt;/code&gt; is pretty basic, and once your files get large enough, totally impractical. Nonetheless, it's a handy function to know about. &lt;/p&gt;

&lt;p&gt;As a useful and comical aside, the function &lt;a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/spit"&gt;&lt;code&gt;spit&lt;/code&gt;&lt;/a&gt; is the counterpart to &lt;code&gt;slurp&lt;/code&gt;, except that instead of reading input, &lt;code&gt;spit&lt;/code&gt; does output. More on this in a future article, though.&lt;/p&gt;

&lt;h4&gt;line-seq&lt;/h4&gt;

&lt;p&gt;One of my favorite IO functions has got to be &lt;code&gt;line-seq&lt;/code&gt;; &lt;code&gt;line-seq&lt;/code&gt; takes a reader object (which must implement &lt;code&gt;BufferedReader&lt;/code&gt;) and returns a lazy sequence of the lines of the text the reader supplies. This is handy when you're dealing with files (if this offends you, let's be Unixy here for now and say that &lt;em&gt;everything is a file&lt;/em&gt;) that are too big to merely &lt;code&gt;slurp&lt;/code&gt;, but that are &lt;code&gt;\newline&lt;/code&gt; delimited (or CR/LF delimited, if you're of the Windows persuasion).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(use '[clojure.java.io '(reader)])
(take 2 
  (line-seq (reader "bobby.txt")))
=&amp;gt; ("Bobby was a good boy," "and didn't complain too much")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice how we &lt;code&gt;take 2&lt;/code&gt; from the sequence we get from using &lt;code&gt;line-seq&lt;/code&gt;. We can &lt;code&gt;take&lt;/code&gt; as much or as little as we need; we won't be reading much (Clojure &lt;a href="http://stackoverflow.com/questions/3247045/how-are-lazy-sequences-implemented-in-clojure/3247417#3247417"&gt;will read a bit more than you tell it to&lt;/a&gt; in order to get more IO performance, but let's not worry about that) more than we specify. We can do anything we want with the resulting seq; that's the beauty of &lt;code&gt;line-seq&lt;/code&gt; and the ubiquitous sequence abstraction. &lt;/p&gt;

&lt;p&gt;Back in the day, Clojurists had to sink a little lower than the &lt;code&gt;clojure.java.io&lt;/code&gt; namespace to use &lt;code&gt;line-seq&lt;/code&gt;; two Java classes were needed. One of these Java classes is the most wondrous and amazing thing just below the surface of the more elegant and beautiful Clojure code; &lt;code&gt;BufferedReader&lt;/code&gt;. Here's how we used to do it; &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(import '(java.io FileReader BufferedReader))
(take 2 
  (line-seq (BufferedReader. 
              (FileReader. "bobby.txt")))
=&amp;gt; ("Bobby was a good boy," "and didn't complain too much")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This might give you a better sense of what's going on when you use &lt;code&gt;reader&lt;/code&gt;, though in reality &lt;code&gt;reader&lt;/code&gt; is far more complicated than just that: you can trust it to handle a variety of "readable things" and return to you a &lt;code&gt;BufferedReader&lt;/code&gt; if possible. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;FileReader&lt;/code&gt; will return a &lt;code&gt;Reader&lt;/code&gt; on a file, and &lt;code&gt;BufferedReader&lt;/code&gt; takes and buffers a &lt;code&gt;Reader&lt;/code&gt;, as you might have extrapolated from the name. &lt;code&gt;Readers&lt;/code&gt; are basically just objects upon which a few methods (like &lt;code&gt;read&lt;/code&gt;, &lt;code&gt;skip&lt;/code&gt; and &lt;code&gt;close&lt;/code&gt;) may be enacted and expected to return reasonable results. &lt;code&gt;line-seq&lt;/code&gt; essentially &lt;code&gt;reads&lt;/code&gt; up until a line-delimiter and returns the read chunk as an element in the sequence it is generating. &lt;/p&gt;

&lt;p&gt;While on the subject of files, I should probably mentioned the &lt;code&gt;file&lt;/code&gt; function, from &lt;code&gt;clojure.java.io&lt;/code&gt;. &lt;code&gt;file&lt;/code&gt; takes in an arbitrary number of string arguments, and pieces them together into a file hierarchy, returning a &lt;code&gt;File&lt;/code&gt; instance. This can come in handy.&lt;/p&gt;

&lt;h4&gt;Rivers? inputStreams? Brooks?&lt;/h4&gt;

&lt;p&gt;Streams are an especially useful class of readers. Oftentimes you're reading in text; that's what &lt;code&gt;Readers&lt;/code&gt; do. But often you need to read in a stream of bytes; that's where you need to use &lt;code&gt;clojure.java.io&lt;/code&gt;'s &lt;code&gt;input-stream&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(use '[clojure.java.io '(reader)])
(def g (input-stream "t.txt"))
(.read g)
=&amp;gt; 105 
(.read g)
=&amp;gt; 115
(char (.read g)) 
=&amp;gt; \space
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, instead of getting characters from this file (like we get when we use a reader), we're getting integer byte values. This can be useful when reading, for example, a media file. &lt;/p&gt;

&lt;p&gt;In general, strings are &lt;em&gt;always&lt;/em&gt; UTF-16, which are 16-bit pieces of data, whereas byte-streams are 8-bit pieces of data. It bears repeating that the stream operators should be used when you're not dealing with strings: they are &lt;em&gt;not&lt;/em&gt; trivially interchangeable, as they might be in other languages where strings are syntactic sugar for byte arrays.&lt;/p&gt;

&lt;h4&gt;RandomAccessFile&lt;/h4&gt;

&lt;p&gt;Finally, let me introduce to you a spectacularly useful Java class. &lt;code&gt;RandomAccessFile&lt;/code&gt; is a class which allows you to quickly jump around in a large file, and read bytes from it. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(import '(java.io RandomAccessFile))
(def f (RandomAccessFile. "stuff.txt" "r"))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the second argument of the constructor, &lt;em&gt;"r"&lt;/em&gt;; this indicates  that we're opening the file just for reading. Now that we have &lt;code&gt;f&lt;/code&gt;, we can use it to navigate and read the file: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(.read f)
=&amp;gt; 105
(.length f)
=&amp;gt; 2015 ;; this is the number of bytes this file is in length
(.skipBytes f 20)
(.getFilePointer h)
=&amp;gt; 21 ;; the position we're at in the file
(.read f)
=&amp;gt; 89
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, you can jump around (quickly!) through a file, and read from the parts you want, and skip the parts you do not want. The key methods/functions here (among many others that can also be useful; be sure to check the &lt;a href="http://download.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html"&gt;documentation&lt;/a&gt;) are &lt;code&gt;read&lt;/code&gt;, &lt;code&gt;length&lt;/code&gt;, &lt;code&gt;skipBytes&lt;/code&gt;, &lt;code&gt;seek&lt;/code&gt; and &lt;code&gt;getFilePointer&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;Closing&lt;/h4&gt;

&lt;p&gt;Every file that is opened should be closed, and what we've been doing is a little unsafe. In order to close an open reader/file, we should use the &lt;code&gt;close&lt;/code&gt; method on it; in the above example, when you're done with &lt;code&gt;f&lt;/code&gt;, simply execute &lt;code&gt;(.close f)&lt;/code&gt; to tell the file system that you're done with the file. Alternatively, and more idiomatically, you can open your files with the handy &lt;code&gt;with-open&lt;/code&gt; binder: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(with-open [f (RandomAccessFile. "stuff.txt" "r")]
           (.read f))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you're done with &lt;code&gt;f&lt;/code&gt;, Clojure will &lt;code&gt;close&lt;/code&gt; it, and you won't have to worry one iota about it. &lt;/p&gt;

&lt;h4&gt;Digging Deeper&lt;/h4&gt;

&lt;p&gt;Should &lt;code&gt;slurp&lt;/code&gt; and &lt;code&gt;line-seq&lt;/code&gt; not be enough for your reading needs (and chances are that, should you code enough in Clojure, they won't always been), you might want to explore &lt;code&gt;clojure.java.io&lt;/code&gt; some more, as well as some of the Java classes (namely, those stemming from &lt;code&gt;Reader&lt;/code&gt; and &lt;code&gt;BufferedReader&lt;/code&gt;, as well as &lt;code&gt;InputStream&lt;/code&gt; and &lt;code&gt;BufferedInputStream&lt;/code&gt;)  mentioned above. See my &lt;a href="http://copperthoughts.com/p/clojurists-guide-to-java/"&gt;previous article on using Java&lt;/a&gt; if you're unfamiliar with using Java.&lt;/p&gt;

&lt;p&gt;Next up is an introduction to the "outs" of Clojure and Java. Stay tuned!&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;&lt;small&gt;I owe a big thank you to &lt;a href="http://technomancy.us/"&gt;Phil Hagelberg&lt;/a&gt; for reading over this essay and offering advice. If you don't already, you should be using his &lt;a href="http://github.com/technomancy/leiningen"&gt;Leiningen&lt;/a&gt; for both dependency management and a stress-free development environment.&lt;/small&gt;&lt;/p&gt;
</description>
          <link>http://copperthoughts.com/p/clojure-io-p1/</link>
          <pubDate>2010-11-13T21:50</pubDate>
        </item><item>
          <title>Fun With Set Theory and Lisp</title>
          <description>&lt;p&gt;A few weeks ago a provoking question was posted on StackOverflow asking if, for example, Common-Lisp's &lt;code&gt;numberp&lt;/code&gt; could be written using only the primitives that John McCarthy presented in &lt;a href="http://www-formal.stanford.edu/jmc/recursive.html"&gt;his now famous essay introducing LISP&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;My answer was yes, but it wasn't the kind of yes you might expect. In his essay, McCarthy did not even mention numbers. There are no primitives to deal with them; only primitives to construct and deconstruct lists (i.e &lt;code&gt;car&lt;/code&gt;, &lt;code&gt;cdr&lt;/code&gt;, &lt;code&gt;cons&lt;/code&gt;), as well as a few to enable the creation and naming of functions (i.e. &lt;code&gt;lambda&lt;/code&gt;, &lt;code&gt;label&lt;/code&gt;). But there are no number primitives: no direct interaction with the ALU, no way to directly access and manipulate integers and floats. So we have figure something else out.&lt;/p&gt;

&lt;h2&gt;It's All Lists From Here&lt;/h2&gt;

&lt;p&gt;So how &lt;em&gt;can&lt;/em&gt; you represent numbers? &lt;/p&gt;

&lt;p&gt;I'm going to eschew using the troublesome &lt;em&gt;cons&lt;/em&gt; cell in my explanations. Instead, we'll use the more common list notation that's both easier to explain and easier to write. Of course, I'll be using the &lt;code&gt;cons&lt;/code&gt; function (how could I &lt;em&gt;not&lt;/em&gt;?) and you should at least have &lt;a href="http://en.wikipedia.org/wiki/Cons"&gt;an idea of how that works&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It turns out that there are a number of ways to represent the natural numbers. Paul Graham postulates one way of representing them &lt;a href="http://www.paulgraham.com/rootsoflisp.html"&gt;in his essay &lt;em&gt;The Roots of Lisp&lt;/em&gt;&lt;/a&gt;. I'll state here, slightly tidied up, his suggestion: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Let the empty list be zero.&lt;/li&gt;
&lt;li&gt;Let 1 = &lt;code&gt;(cons 0 ())&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Let 2 = &lt;code&gt;(cons 1 ())&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this way we can represent all the natural numbers. It'd be trivial to write a function &lt;code&gt;number?&lt;/code&gt; that would test to see if if its argument had the form of a number. There are a number (hah!) of things we could do with this representation, but I think we can do better.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Edit&lt;/strong&gt;: &lt;a href="http://technomancy.us/"&gt;Phil Hagelberg&lt;/a&gt; reminds me of another, very important, representation of the natural numbers I'd be remiss to leave out: the &lt;a href="http://en.wikipedia.org/wiki/Church_encoding"&gt;Church Encoding&lt;/a&gt;. Church Encoding is way of representing the natural numbers using only lambda calculus: there are no lists involved. Instead, a number &lt;em&gt;n&lt;/em&gt; is representing by a higher order lambda abstraction (a function), and returns the result of that function being composed with itself &lt;em&gt;n&lt;/em&gt; times. There's actually a fair amount that can be done with this representation, but it's outside the scope of this essay. For the curious, the afore-linked Wikipedia article does a fine job of covering the basics. &lt;/p&gt;

&lt;h2&gt;The More Lists, the Merrier&lt;/h2&gt;

&lt;p&gt;But really, that's not enough lists, is it?  &lt;code&gt;(((((((((())))))))))&lt;/code&gt; is not nearly an unwieldy enough definition for 10. We need more lists.&lt;/p&gt;

&lt;p&gt;Let's take a step back and look at set theory; a branch of math and CS that's informed a lot of underpinning of CS and programming in general. Set theory has already provided us with a handy way of defining numbers based on lists. Well not lists, &lt;em&gt;sets&lt;/em&gt;, but sets are basically lists. In fact, contrary to popular/programming belief, sets can hold the same thing multiple times, but in set theory that means nothing. We'll say the same thing about lists: "when you say my list &lt;em&gt;a&lt;/em&gt; contains &lt;em&gt;b&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt;, I just hear that &lt;em&gt;b&lt;/em&gt; is in &lt;em&gt;a&lt;/em&gt;". &lt;/p&gt;

&lt;p&gt;So how do we represent numbers using only sets? Well, we start with the empty set &lt;code&gt;{}&lt;/code&gt; being zero. But, and here's where things get weird, we now define a function &lt;em&gt;S&lt;/em&gt; called the "successor function". The successor of &lt;em&gt;n&lt;/em&gt; is the union of &lt;em&gt;n&lt;/em&gt; and the set of &lt;em&gt;n&lt;/em&gt;, where &lt;code&gt;union&lt;/code&gt; is a function of &lt;em&gt;n&lt;/em&gt; and &lt;em&gt;m&lt;/em&gt; that returns the set which contains all the elements in &lt;em&gt;n&lt;/em&gt; and all the elements in &lt;em&gt;m&lt;/em&gt;.  &lt;em&gt;S(n) = {n and all the elements in n}&lt;/em&gt;. To make this clearer, let's look at a few examples. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;S(0) = union(0 {0}) = {0} ;; we'll call this 1
S(1) = union(1 {1}) = union({0} {{0}}) 
       = {0 {0}} ;; and this 2
S(2) = {0 1 2}  ;; 3
S(3) = {0 1 2 3} ;; 4
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At the very least, this is an interesting definition of the natural numbers. The predecessors of each number are contained within it. And the set of &lt;em&gt;all&lt;/em&gt; the natural numbers has a form similar to an individual natural number. Neat. &lt;/p&gt;

&lt;p&gt;Let's see how we can represent this with lists. Our goal is a function, &lt;em&gt;S&lt;/em&gt;, that returns the successor of a given list. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define S
  (lambda (n)
    (union n (cons n ()))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Perfect, though we don't exactly have a union function yet: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define union 
  (lambda (n m)
    (cond ((null? n) m)
           (else (cons (car n)
                       (union (cdr n) m))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we do. You can test it out in your own REPL, or online with &lt;a href="http://tryscheme.sourceforge.net/"&gt;TryScheme&lt;/a&gt;. We're going to move on now. &lt;/p&gt;

&lt;h2&gt;So What?&lt;/h2&gt;

&lt;p&gt;Thats a valid question. At this point, it seems as though we've merely complicated Mr. Graham's elegant and simple proposition. It turns out that we've actually made things easier, in the long run. &lt;/p&gt;

&lt;p&gt;Before we even get to addition and the like, let's look at one example of where we've made things easier and more elegant. Let's look at an ordering on the natural numbers; &lt;code&gt;&amp;lt;&lt;/code&gt;. With this definition, we don't need anything else to define it: &lt;em&gt;n&lt;/em&gt; &amp;lt; &lt;em&gt;m&lt;/em&gt; if (and only if) &lt;em&gt;n&lt;/em&gt; is in &lt;em&gt;m&lt;/em&gt;. That's a straight forward definition, and one we can check rather quickly with a Lisp function you might have on hand anyway (&lt;a href="http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992#reader_0262560992"&gt;&lt;em&gt;The Little Schemer&lt;/em&gt;&lt;/a&gt; calls it &lt;code&gt;member?&lt;/code&gt;). &lt;/p&gt;

&lt;p&gt;But first we need a better &lt;code&gt;eq?&lt;/code&gt;. The current &lt;code&gt;eq?&lt;/code&gt; operates only on atoms; we need an &lt;code&gt;equal?&lt;/code&gt; that works on our list representation of numbers. To keep things simple, we're going to assume our lists are ordered. That will be the case if we build our numbers with just &lt;em&gt;S&lt;/em&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define equal?
  (lambda (n m)
    (cond ((and (null? n) (null? m)) #t)
          ((or (null? n) (null? m)) #f)
          (else (and (equal? (car n) (car m))
                     (equal? (cdr n) (cdr m)))))))

(define member?
  (lambda (a l)
    (cond ((null? l) #f)
          (equal? a (car l)) #t)
          (else (member? a (cdr l))))))

(define &amp;lt;
    (lambda (n m)
       (member? n m)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works because all our natural numbers are either the empty list or a list of natural numbers, thanks to our nicely defined &lt;em&gt;S&lt;/em&gt; function. &lt;/p&gt;

&lt;p&gt;It turns out that this successor function is also nice for defining and working with ideas like ordinals and cardinals, and just generally makes out theorems easier to prove and reason about. But, without writing a book on it, suffice it to say there's a certain elegance about it. I'll leave it at that. &lt;/p&gt;

&lt;h2&gt;In Addition…&lt;/h2&gt;

&lt;p&gt;But back to our problem: numbers on a simple Lisp machine. We've now got a suitable representation of the natural numbers (though I've neglected to introduce the axioms required to fully justify this; let's just use common sense and carry on), and we have a way of comparing two numbers. &lt;/p&gt;

&lt;p&gt;We also have a way of adding one to a number in &lt;em&gt;S&lt;/em&gt;. How about adding two natural numbers together?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define zero?
  (lambda (n)
    (equal? () n)))

(define A 
  (lambda (n m)
    (cond ((zero? m) n)
          (else (S (A n (P m)))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That is a nice recursive definition, but we have a mysterious new &lt;em&gt;P&lt;/em&gt; function now, as well. &lt;em&gt;P&lt;/em&gt; stands for "predecessor", and it gives us the natural number than &lt;em&gt;m&lt;/em&gt; is a successor of. &lt;/p&gt;

&lt;p&gt;Before defining &lt;em&gt;P&lt;/em&gt;, let me present the set theoretical definition of addition: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;A(n, 0) = n&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;A(n, S(m)) = S(A(n, m))&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is also recursive, but it has the unfair advantage of what the Clojurist in me calls the "de-structuring" of its operands. &lt;em&gt;A&lt;/em&gt; can check to see if its second operand is a successor, and if it is will take the successor of the result of another &lt;em&gt;A&lt;/em&gt;'s value. &lt;/p&gt;

&lt;p&gt;With Lisp, we can check to see is &lt;em&gt;m&lt;/em&gt; is zero, and if it isn't, we know that it is a successor, we just don't know what it is a successor &lt;em&gt;of&lt;/em&gt;. That is where &lt;em&gt;P&lt;/em&gt; comes in. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define R
  (lambda (fn acc l)
     (cond ((null? l) acc)
           (else (R fn (fn acc (car l)) (cdr l))))))

(define P
  (lambda (n)
    (cond ((zero? n) #f) ;; really, undefined
          (else (R union () n)))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And out of nowhere comes a higher-order function! While set theory may have some expressive advantages over Lisp, we've got some special sauce, too. In this case &lt;code&gt;(R union () n)&lt;/code&gt; is equivalent to the set theoretical "union over a set" that the &lt;a href="http://en.wikipedia.org/wiki/Zermelo-Fraenkel_set_theory"&gt;Zermelo-Fraenkel&lt;/a&gt; Union Axiom gives provides. Most people call &lt;em&gt;R&lt;/em&gt; "reduce".&lt;/p&gt;

&lt;p&gt;You might notice that we get duplicates in our lists, but as I said before, we don't pay those any attention. To keep things clean and  working well, we'll implicitly apply a helper function, &lt;code&gt;distinct&lt;/code&gt;, to the result of every operation. &lt;code&gt;distinct&lt;/code&gt; is left as an exercise to the reader; but this is a very important exercise: some of our function will &lt;em&gt;not&lt;/em&gt; work if &lt;code&gt;distinct&lt;/code&gt; isn't applied to the result of each function. &lt;/p&gt;

&lt;p&gt;With a proper &lt;em&gt;P&lt;/em&gt; defined, &lt;em&gt;A&lt;/em&gt; now works flawlessly. Now let's define &lt;em&gt;M&lt;/em&gt;, multiplication and &lt;em&gt;B&lt;/em&gt;, subtraction:  &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define M
  (lambda (n m)
    (cond ((zero? m) ())
          (else (A n (M n (P m)))))))

(define B                                                         
  (lambda (n m)
    (cond ((zero? m) n)
          (else (P (B n (P m)))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It gets easier and easier as we build off of our previous functions, and combine them to yield more complex, more useful abstractions. Finally, let's write our number predicate; &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define length
  (lambda (n)
    (cond ((null? n) ())
          (else (S (length (cdr n)))))))

(define number?
  (lambda (n)
    (equal? n (length n))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And there you have it; we've got the basics of our natural numbers, represented using McCarthy's basic LISP. &lt;/p&gt;

&lt;h2&gt;But, Wait! There's More&lt;/h2&gt;

&lt;p&gt;Ah, we've left off the integers. And floats! &lt;/p&gt;

&lt;p&gt;Fortunately, this isn't a big deal. With our newly defined natural numbers, we can represent integers as a tuple of natural numbers, where the first natural number in the tuple represents the "negative" portion of the integer, and the second natural number represents the "positive" portion of the integer. &lt;/p&gt;

&lt;p&gt;In this manner we can represent all the integers. Of course, we'll have to create new functions for adding, subtracting and the like, but that becomes a matter of building new, higher level abstractions with our existing functions. &lt;/p&gt;

&lt;p&gt;For example, we can define adding two integers like this: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define first
  (lambda (n)
    (car n)))

(define second 
  (lambda (n)
    (car (cdr n))))

(define makeint
  (lambda (n p)
    (cons n (cons p ()))))

(define A2
  (lambda (x y)
     (makeint (A (first x) (first y)) 
              (A (second x) (second y)))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Something important to keep in mind, however, is that different tuples can represent the same integer. For instance, the integer (2, 5) is the same as the integer (0, 3); they're both what we would have called "3" back in the natural numbers section. In fact, it makes sense to call both of them "3" here. But the second example here is preferable, I'd say. This is something that is dealt with in set theory by &lt;a href="http://en.wikipedia.org/wiki/Equivalence_relation"&gt;equivalence relations&lt;/a&gt;; we can do the same thing in Lisp. Below I'll define a function which returns the "simplest" version of a given integer; one where either the negative portion is zero, the positive portion is zero, or they are both zero.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(define simplint
  (lambda (z)
    (cond ((or (zero? (first z)) (zero? (second z))) z)
          (else (makeint (P (first z)) 
                         (P (second z)))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Subtraction, multiplication and other operations on integers begin to fall into place with these definitions. Things don't get more complicated as you move further away from your base representation (unless you try to formally prove all of my assertions): if anything, they get easier. This is a consequence of appropriate abstraction. &lt;/p&gt;

&lt;p&gt;So far, we have arbitrarily large integers available to us (limited in practice only by memory and processing power). But we're still missing a type of number most programmers expect to have available to them: the float. Well, we can do that too. &lt;/p&gt;

&lt;p&gt;First, let's make sure we know what a float can and cannot represent. Floats can't represent all real numbers: that is to say, every float is representable by a ratio of two numbers. In fact, traditional floats can't even represent all rationals: for instance, 1/3 is 0.333… repeating forever. We would run out of bits to represent it on a real computer. But we can represent all numbers a float can, and more, with ratios. And, as I'm sure has now become clear, we definitely have ratios in the form of a tuple of integers, the first representing the numerator and the second the denominator. These are the rational numbers.&lt;/p&gt;

&lt;p&gt;Again, an equivalence relation on the rationals is called for, as are new operations. This time, though, they are left as an exercise for the reader. &lt;/p&gt;

&lt;h2&gt;Final Words&lt;/h2&gt;

&lt;p&gt;Though a lot more can be said about the intersection of set theory and Lisp, I'll stop while this post is still of Internet-length. If there's enough interest (mostly on my part), perhaps this will be extended into a series of essay on the subject, mirroring the progression of a elementary set theory book.&lt;/p&gt;

&lt;p&gt;This essay is a product of my investigation into the possibility of a truly programmable and reprogrammable Lisp environment, one in which such a definition of the natural, integer and rational numbers would not only be feasible and efficient, but idiomatic. I'm a long way from explaining how such a system would work, but I thought I should record at least some of the byproducts of my thought process so that someone might obtain some value from my mental wanderings.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;I should note that while I used the operators &lt;code&gt;and&lt;/code&gt; and &lt;code&gt;or&lt;/code&gt;, neither were in McCarthy's original LISP. Consider &lt;code&gt;(and a b)&lt;/code&gt; a stand-in for &lt;code&gt;(cond (a b) (else #f))&lt;/code&gt; and &lt;code&gt;(or a b)&lt;/code&gt; for &lt;code&gt;(cond (a #t) (else b))&lt;/code&gt;, and all is well. &lt;/p&gt;

&lt;p&gt;If there are errors in my explanations or code samples, please let me know. I certainly simplified much of the content so that it could fit in about 2000 words, but it should be correct.&lt;/p&gt;
</description>
          <link>http://copperthoughts.com/p/set-theory-and-lisp/</link>
          <pubDate>2010-09-01T15:40</pubDate>
        </item>
        
        
    </channel>
</rss>
