Destructuring in a Function's Argument List

Clojure never ceases to amaze. In a function I was writing, I wanted to have an optional argument at the end, and I knew to use the "&" symbol in the argument list, like this:

(defn foo [& argument-sequence] ... )

But then I realized that I wanted to call foo with zero, one, or two arguments. What if I did (second foo) and that crashed the program? What if I wanted to set the second argument but not the first? Am I going to have to write a weird rat's-nest of nested if statements (probably containing some bugs)? I thought Clojure would let me get away from this.

It turns out I was right.

I thought I had read something about using destructuring1 within a function's argument list. So I thought, why not just try it? Here's what I wrote:

(defn foo [& [text font]]
  (println "text=" text ", font=" font))

(foo "hello" (make-font "Monospaced" Font/PLAIN 36))
(foo "hello")
(foo)

The three tests in the code above return the following:

text= hello , font= #<Font java.awt.Font[family=Monospaced, 
    name=Monospaced,style=plain,size=36]>
text= hello , font= nil
text= nil , font= nil

This quick experiment told me what I needed to know: yes, you can do restructuring in a function's argument list and if there's no value there, the bound symbol returns nil.

Good hacking!

(written 10/24/10)


Comments

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License