Thursday, 31 December 2009

ACL: Chapter 1

In Chapter 1, Graham writes:
Suppose instead you want to write a function that takes a number n, and returns a function that adds n to its argument. (ANSI Common Lisp, p.1-2)
He then gives a simple lambda function that implements this functionality. The 2 Clojure alternatives that I have come up with are:
;; p.2 - form using explicit fn syntax
(defn addn [n]
  (fn [x] (+ x n)))
And the terser form:
;; p.2 - use the terse form of anonymous function
(defn addn-terse [n]
  #(+ % n))
In my first I had too many brackets in the terser form which led to a cryptic error:
;; p.2 - incorrect form of anonymous function
(defn addn-terse-incorrect [n]
  (#(+ % n)))
Leads to the error:
com.nwalex.clj.acl-chpt1=> (addn-terse-incorrect 6)
java.lang.IllegalArgumentException: Wrong number of args passed to: acl-chpt1$addn-terse-incorrect--523$fn (NO_SOURCE_FILE:0)>
In my opinion sweating blood is the best way to learn. The terse form of the anonymous function is now thoroughly embedded in my brain because I had to work out why my original attempt wasn't working. You can't learn something like that simply by reading a book.

No comments:

Post a Comment