Search This Blog

Saturday, September 11, 2010

Clojure Macro Tutorial (Part I, Getting the Compiler to Write Your Code For You)

I am asked to point out that this is part of a series, following the form of the Ring Cycle, although not directly inspired by it. Syntax Quote plays the role of Siegfried in part III.

http://www.learningclojure.com/2010/09/clojure-macro-tutorial-part-i-getting.html http://www.learningclojure.com/2010/09/clojure-macro-tutorial-part-ii-compiler.html http://www.learningclojure.com/2010/09/clojure-macro-tutorial-part-ii-syntax.html

Suggestions for Götterdämmerung will be most welcome.

;; A couple of chaps have asked me to write a clojure macro tutorial, to explain
;; my debugging macro:

(defmacro dbg[x] `(let [x# ~x] (println '~x "=" x#) x#))

;; Which I use to print out intermediate values in functions.

;; Here's an example function that we might want to debug:
(defn pythag [ x y ] (* (* x x) (* y y)))

;; And here is a version enhanced to print out its thought process as it runs
(defn pythag [ x y ]  (dbg (* (dbg (* x x)) (dbg (* y y)))))

(pythag 4 5)
;; (* x x) = 16
;; (* y y) = 25
;; (* (dbg (* x x)) (dbg (* y y))) = 400
;; 400

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; I'm going to try to imagine that I didn't know how to write dbg, and had to
;; go at it by trial and error, to show why it is as it is.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The problem that dbg solves:

;; Often the best way to debug code is by adding print statements.

;; Consider our old friend factorial

(defn factorial [n]
  (if (< n 2) n
      (* n (factorial (dec n)))))

(factorial 5) ;; 120

;; How would we watch it at work?
;; This modified version prints out the value of every recursive call:

(defn factorial [n]
  (if (< n 2) n
      (* n (let [a (factorial (dec n))]
             (println "(factorial (dec n))=" a)
             a))))

(factorial 5)
;;(factorial (dec n))= 1
;;(factorial (dec n))= 2
;;(factorial (dec n))= 6
;;(factorial (dec n))= 24
;;120

;; So now we can watch the stack unwind. This gives us confidence in the inner
;; workings of the function.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The problem with this solution is that I've had to do a fair bit of typing to
;; change the function into a version that prints out its intermediate values.

;; First, let's give n a global value so that we can evaluate fragments out of
;; context:
(def n 5) 

;; Here's the original function again (re-evaluate the definition)
(defn factorial [n]
  (if (< n 2) n
      (* n (factorial (dec n)))))

;; Specifically, what I had to do was change
(factorial (dec n))
;; into
(let [a (factorial (dec n))] (println "(factorial (dec n))=" a) a)

;; Which is an expression which not only evaluates to 24 when n=5 , like the
;; original did, but which prints out (factorial (dec n))= 24 at the same time.

;; Notice that the phrase (factorial (dec n)) has to be repeated in the code.

;; Every time I would like to examine the value returned by an expression as my
;; program runs, I have to make this complicated but mechanical change. Even
;; more annoyingly, I have to tell the compiler the same thing twice.

;; Any time you find that you have to do too much typing and perform mechanical
;; repetitions, you will also find difficulty in reading, and potential for
;; error. It is always to be avoided.

;; As Larry Wall said, the chief virtue of a programmer is laziness.

;; This simple repetitive task should be as easy as changing
(factorial (dec n))
;; to
(dbg (factorial (dec n)))

;; Normally, when one spots a common pattern like this, one makes a function.
;; But a function to do what we want here is problematical, because we need the
;; source code as well as the evaluated value of (factorial (dec n)) We might
;; try something like:
(defn dbgf [s x]
  (println s "=" x)
  x)

;; And use it like this:
(defn factorial [n]
  (if (< n 2) n
      (dbgf "(* n factorial(dec n))" (* n (factorial (dec n))))))
  
;; That's a bit better, but I'm still changing
(* n (factorial (dec n)))
;; into 
(dbgf "(* n factorial(dec n))" (* n (factorial (dec n))))

;; Which is less error prone, but still repetitive.

;; The reason that we need to hold dbgf's hand like this, telling it what to
;; print out in two different ways, is that a function's arguments are evaluated
;; before the function is called.

;; If we want to write
(dbg (* n (factorial (dec n))))
;; and have it work as we intend, then we need to take control of when
;; (* n (factorial (dec n))) is evaluated.

;; And this is the problem that macros solve.

;; We need to work out how to write:
(dbg (* n (factorial (dec n))))
;; And get:
(let [a (factorial (dec n))] (println "(factorial (dec n))=" a) a)
;; Instead.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Generating Code

;; Now because lisp code and lisp data are very similar things, we can easily
;; write a function which will generate the code that we want:

;; Let's define:
(defn dbg-code [s]
  (list 'let ['a s] (list 'println (list 'quote s) "=" 'a) 'a))
;; Which is just a function that takes some code and gives back some code.

;; We can call this function on little pieces of code, to get other little
;; pieces of code

(dbg-code 'x)
;; (let [a x] (println (quote x) "=" a) a)

(dbg-code '(* x x))
;; (let [a (* x x)] (println (quote (* x x)) "=" a) a)

(dbg-code '(* n (factorial (dec n))))
;; (let [a (* n (factorial (dec n)))] (println (quote (* n (factorial (dec n)))) = a) a)

;; Nothing 'macro' has gone on yet! This is just a function, taking advantage of
;; lisp's ability to easily deal with the lists and trees and vectors that make
;; up lisp code.

;; But the function generates exactly the code that we'd like the compiler to
;; substitute in.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Macros

;; Now how shall we turn our code-generating function into a macro?
;; Just change defn to defmacro:

(defmacro dbg-1 [s]
  (list 'let ['a s] (list 'println (list 'quote s) "=" 'a) 'a))

;; Now it's a macro!

;; Let's try it out:
(defn factorial [n]
  (if (< n 2) n
      (dbg-1 (* n (factorial (dec n))))))

(factorial 5)
;; (* n (factorial (dec n))) = 2
;; (* n (factorial (dec n))) = 6
;; (* n (factorial (dec n))) = 24
;; (* n (factorial (dec n))) = 120
;; 120

;; Bingo!

;; When the compiler sees a macro, which is just a function that returns some
;; code, it runs the function, and substitutes the code that is returned into
;; the program.

;; It is like programming the compiler to be an apprentice programmer who will
;; write out the tedious bits longhand for you.

;; We can even ask the compiler what it sees when it expands dbg-1:
(macroexpand-1 '(dbg-1 x))
;; (let [a x] (println (quote x) "=" a) a)
(macroexpand-1 '(dbg-1 (* x x)))
;; (let [a (* x x)] (println (quote (* x x)) "=" a) a)
(macroexpand-1 '(dbg-1 (println x)))
;; (let [a (println x)] (println (quote (println x)) "=" a) a)
(macroexpand-1 '(dbg-1 (inc x)))
;; (let [a (inc x)] (println (quote (inc x)) "=" a) a)
(macroexpand-1 '(dbg-1 (* n (factorial (dec n)))))
;; (let [a (* n (factorial (dec n)))] (println (quote (* n (factorial (dec n)))) "=" a) a)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; So have we won??

;; We have certainly solved our problem as we originally conceived it, but there
;; are potentially a couple of difficulties with our solution, which I shall
;; cover in a later post.

;; Neither are terribly likely to occur in practice, but it is better to write
;; bug-free code than almost-bug-free code.

;; The chief virtues of a programmer are laziness and paranoia.
;; Million to one chances have a way of coming up nine times out of ten.

;; Also, compare our solution with the actual dbg macro:

(defmacro dbg-1 [s]
  (list 'let ['a s] (list 'println (list 'quote s) "=" 'a) 'a))

(defmacro dbg[x] `(let [x# ~x] (println '~x "=" x#) x#))

;; There are obviously similarities, but the complete version looks more like
;; the generated code, and is thus easier to write and to read once you've got
;; the hang of the weird `, #, and ~ things.

;; And the second version also solves the two potential difficulties which I
;; haven't explained yet!


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Things to play with to check you've understood:

;; I. Find the source for clojure.core/when
(clojure.repl/source when)
;; figure out what it does.

;; II. What is wrong with:
(defmacro dbg-oops [s]
  (list 'do (list 'println (list 'quote s) "=" s) s))

;; III. Can you improve dbg so you can write (dbg * 3 2) rather than
;; (dbg (* 3 2)), saving a couple of brackets every time you use it?

;; IV. Using the methods above, can you write a for loop. We'd want
(forloop [i 1 10]
  (print i)
  (print (* i i)))

;; to expand to:
(loop [i 1]
  (when (<= i 10)
    (print i)
    (print (* i i))
    (recur (inc i))))

;; V. (hard) If you managed to do IV above, and write forloop, then congratulations! ;; You have
;; understood this post. But I bet your solution suffers from either or both of
;; the subtle problems that I mentioned above. Can you work out what they are?

;; Hint. How many times does the finish condition get evaluated as you go
;; through the loop? How would you make sure that only happened once? What if a
;; name you'd used in the macro clashed with a name used in the code where the
;; macro is?

;; Both problems are, in fact, easy to solve. See part II.




Thursday, September 9, 2010

defn vs defmacro: What is a macro? Why is it different from a function?

The question "What is the difference between defn and defmacro" came up on Stack Overflow http://stackoverflow.com/questions/3667403/what-is-the-difference-between-the-defn-and-defmacro/3668091#3668091

Here is my answer, which combines my little debugging macro (which I miss in every non-lisp programming language that I use) with 'the story of mac'.

I worry that I might have over-simplified when I was trying to be clear.

Remember that the question is being asked by someone who does not already understand the answer. Have I misspoken or misled here?



;; A macro is like having an apprentice programmer that you can write notes to:

;; Sometimes, if I'm trying to debug something, I like to change something like

    (* 3 2)

;; Into something like this:

    (let [a (* 3 2)]
      (println "dbg: (* 3 2) = " a)
      a)

;; Which works the same way, except that it prints out the expression it has
;; just evaluated, and its value, as well as returning the value as the result
;; of the whole expression. This means that I can leave my code undisturbed
;; whilst examining intermediate values.
 
;; This can be very useful, but it's time consuming and error prone to type. You
;; might imagine delegating such tasks to your apprentice!

;; One way to do that would be to write (dbg (* 3 2)) and leave to your
;; apprentice the mechanical task of turning that into the above code.

;; Rather than hiring an apprentice, you can program the compiler to do these
;; things for you:

    ;;debugging parts of expressions
    (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#))

;; Now try:

    (* 4 (dbg (* 3 2)))

;; The compiler actually makes the textual transformation on the code for you,
;; although being a computer, it chooses unreadable names for its variables
;; instead of the "a" I would have chosen.

;; We can ask it what it would do for a given expression:

    (macroexpand '(dbg (* 3 2)))

;; And this is its answer, so you can see that it really is rewriting the code
;; for you:

    (let* [x__1698__auto__ (* 3 2)]
          (clojure.core/println "dbg:" (quote (* 3 2)) "=" x__1698__auto__)
          x__1698__auto__)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Try to write a function dbgf that does the same thing, and you'll have
;; problems, because (dbgf (* 3 2)) -> (dbgf 6) before dbgf is called, and so
;; whatever dbgf does, it can't recover the expression that it needs to print
;; out.

;; I'm sure you can think of many ways round this, like run-time evaluation or
;; passing in a string. Try to write dbg using defn instead of defmacro. It will
;; be a good way to convince yourself that macros are good things to have in a
;; language. Once you've got it working, try using it on an expression that has
;; a side effect as well as a value, like:

    (dbg (print "hi"))

;; (In fact macros are so good to have that we're prepared to live with the
;; (brackety ((syntax))) of LISPs in order to get them. (Although I must say
;; that I rather like it for its own sake (but then (I am) a bit weird (in the
;; head.))))

;; C also has macros, which work in roughly the same way, but they're always
;; going wrong, and to get them right you need to put so many brackets into your
;; program that it looks like LISP!

;; You're actually recommended not to use C's macros because they're so error
;; prone, although I have seen them used to great effect by people who really
;; knew what they were doing.

;; LISP macros are so effective that the language itself is built out of them,
;; as you'll notice if you look at the Clojure source files that are themselves
;; written in Clojure.

;; The base language is very simple so that it's easy to implement, and then the
;; complex superstructure is built up using macros.

Monday, September 6, 2010

reduce-seq: An Exercise in Laziness and Futility

;; A futile design process

;; The other day, I found myself wanting a running average of an infinite sequence

;; Here is an example of such a sequence:
(def integers (iterate inc 0))

;; At first, I took the easy way out by just calculating it
(defn runavg [sq]
     (fn [n]
       (/ (reduce + (take (inc n) sq))
          (inc n))))

;; So here is the fifth running average
((runavg integers) 5)

;; After a while, I had occasion to make a list of the running averages themselves
(def runavgs (map (runavg integers) (iterate inc 0)))

(take 5 runavgs)

;; this list proved very useful, but Schlemiel the Painter is at work here:

(time (count (take 100    (map (runavg integers) (iterate inc 0))))) ;;12ms
(time (count (take 1000   (map (runavg integers) (iterate inc 0))))) ;;1200ms
;; (time (count (take 10000 (map (runavg integers) (iterate inc 0))))) ;;120s
;; (time (count (take 100000 (map (runavg integers) (iterate inc 0))))) ;;3 hours

;; This wasn't a problem for my program as first written, but as I pushed it
;; further this became a major bottleneck, and so I decided to optimize the
;; running average to only look at each element once.
(defn runavg
  ([lst] (runavg 0 0 lst))
  ([sum count lst]
     (if (empty? lst) '()
         (let [newsum (+ sum (first lst))
               newcount (inc count)]
           (cons (/ newsum newcount)
                 (runavg newsum newcount (rest lst)))))))

(runavg '(1 2 3 4 5))

;; Of course, we can make this work for infinite sequences too just by wrapping
;; the function with lazy-seq
(defn runavg
  ([lst] (runavg 0 0 lst))
  ([sum count lst]
     (lazy-seq
      (if (empty? lst) '()
          (let [newsum (+ sum (first lst))
                newcount (inc count)]
            (cons (/ newsum newcount)
                  (runavg newsum newcount (rest lst))))))))

(take 5 (runavg integers))

;; Performance, predictably is vastly improved. 
(time (count (take 100    (runavg integers))))) ;;0.3ms
(time (count (take 1000   (runavg integers))))) ;;3ms
(time (count (take 10000  (runavg integers))))) ;;30ms
(time (count (take 100000 (runavg integers))))) ;;300ms


;; Now, in this new algorithm, we have an accumulator, which stores the sum of
;; the elements so far And another which stores the count so far, and this
;; automatically made me think of reduce:
(reduce + (range 1 10))                       ;;summing with reduce
(reduce (fn[a x] (inc a)) (range 1 10))       ;;counting with reduce

;; Of course we can combine these two reductions
(reduce (fn [[sum count] x] [(+ sum x) (inc count)]) [0 0] (range 1 10))

;; But if we want a running average, as above, then we'd really like to see the
;; state of the accumulator at every step, and also, reduce will blow up on an
;; infinite sequence.

;; And so it occurred to me that I could write a lazy version of reduce, which I called
;; reduce-seq
 
(defn reduce-seq [f acc sq]
  (if (empty? sq) (list acc)
      (let [next-acc (f acc (first sq))]
        (cons acc (reduce-seq f next-acc (rest sq))))))

;; Now, it's a simple matter to lazy this up:
(defn reduce-seq [f acc sq]
  (lazy-seq
   (if (empty? sq) (list acc)
       (let [next-acc (f acc (first sq))]
         (cons acc (reduce-seq f next-acc (rest sq)))))))

;; Here are some trivial reductions
(reduce-seq + 0 '(0 1 2 3 4 5))             ;; (0 1 3 6 10 15)
(take 5 (reduce-seq + 0 integers)))         ;; (0 0 1 3 6)
(take 5 (reduce-seq * 1 (drop 1 integers))) ;; (1 1 2 6 24)

;; A new way to define the factorials is always pleasing, and the laziness makes
;; it pretty efficient!

;; Here's it working with the function and accumulator above
(reduce-seq
 (fn [[sum count] x] [(+ sum x) (inc count)])
 [0 0]
 (range 5)) ;;([0 0] [0 1] [1 2] [3 3] [6 4] [10 5])

;; And here's how we could use it to define runavg
(defn running-average [sq]
  (map #(apply / %)
       (drop 1
             (reduce-seq
              (fn [[sum count] x] [(+ sum x) (inc count)])
              [0 0]
              sq))))

(running-average (range 5))          ;; (0 1/2 1 3/2 2)
(take 10 (running-average integers)) ;; (0 1/2 1 3/2 2 5/2 3 7/2 4 9/2)

;; So at this point, I was starting to feel pretty smug.
;; A new version of factorial, and a functional abstraction like map, filter, and reduce that
;; seemed to be more general than any of them, and adapted for infinite sequences besides.
;; I'd never seen anything like that before.

;; And it occurred to me that if I was going to generalize reduce, I'd better deal with
;; the case where the first value of the sequence is used as the initial accumulator too:
(defn reduce-seq
  ([f acc sq]
     (lazy-seq
      (if (empty? sq) (list acc)
          (let [next-acc (f acc (first sq))]
            (cons acc (reduce-seq f next-acc (rest sq)))))))
  ([f sq] (reduce-seq f (first sq) (rest sq))))

;; reduce-seq should work as much like reduce as possible

(reduce     + 0 '(1 2 3 4 5))     ;; 15
(reduce-seq + 0 '(1 2 3 4 5))     ;; (0 1 3 6 10 15)
(reduce     +   '(1 2 3 4 5))     ;; 15
(reduce-seq +   '(1 2 3 4 5))     ;; (1 3 6 10 15)
(reduce + 0 (range 4)) ;;6
(take 5 (reduce-seq + 0 (iterate inc 0))) ;; (0 0 1 3 6)
(reduce + 0 '())     ;; 0
(reduce-seq + 0 '()) ;; (0)

;; So far so good, but I've violated the principle of least surprise here:
(reduce + '())     ;; 0
(reduce-seq + '()) ;; (nil)

;; Here's a regression test that will allow me to mess about with the function
;; while preserving its good behaviours
(defn test-reduce-seq [reduce-seq]
  (cond (not= (reduce-seq + 0 '(1 2 3 4 5)) '(0 1 3 6 10 15)) "fail"
        (not= (reduce-seq +   '(1 2 3 4 5)) '(1 3 6 10 15))    "fail"
        (not= (take 5 (reduce-seq + 0 (iterate inc 0))) '(0 0 1 3 6)) "fail"
        (not= (reduce-seq + 0 '()) '(0)) "fail"
        (not= (reduce-seq +   '(1))   '(1)) "fail"
        (not= (reduce-seq + 1 '(1))    '(1 2)) "fail"
        (not= (nth (reduce-seq + (iterate inc 0)) 10000) (* 1/2 10000 10001)) "fail"
        (not= (reduce-seq #(assoc %1 %2 (inc (get %1 %2 0))) {} "aab")
              '({} {\a 1} {\a 2} {\b 1, \a 2})) "fail"
        (not= (reduce-seq + '()) '(0)) "fix me!!"
        :else "pass"))

(test-reduce-seq reduce-seq)

;; We can slightly shorten the function by noticing that we add the accumulator to
;; the sequence whether the sequence is empty or not.
(defn reduce-seq
  ([f acc sq]
     (lazy-seq
      (cons acc
            (if (empty? sq) '()
                (let [next-acc (f acc (first sq))]
                  (reduce-seq f next-acc (rest sq)))))))
  ([f sq] (reduce-seq f (first sq) (rest sq))))

(test-reduce-seq reduce-seq)

;; It's for some reason considered better style with the lazy functions to use when-let and seq
;; instead of if and empty?

;; If we swap the arms of the if statement:
(defn reduce-seq
  ([f acc sq]
     (lazy-seq
      (cons acc
            (if-let [sq (seq sq)]
              (let [next-acc (f acc (first sq))]
                (reduce-seq f next-acc (rest sq)))
              '()))))
  ([f sq] (reduce-seq f (first sq) (rest sq))))

(test-reduce-seq reduce-seq)

;; and then notice that (cons a (if-let b c '()))
;; is equivalent to     (cons a (when-let b c))
;; then we can shorten the function yet further, and put it into this 'house style'
(defn reduce-seq
  ([f acc sq]
     (lazy-seq
      (cons acc
            (when-let [sq (seq sq)]
              (reduce-seq f (f acc (first sq)) (rest sq))))))
  ([f sq] (reduce-seq f (first sq) (rest sq))))

(test-reduce-seq reduce-seq)

;; This actually looks a bit the wrong way round to me, but it's shorter than
;; the original, so it's probably just a matter of getting used to this style in
;; the same way that I'm used to the SICP style of putting the empty case first.


;; Having put it into the house style, we can fix the bug with the empty list
;; and no accumulator:
(defn reduce-seq
  ([f acc sq]
     (cons acc
           (lazy-seq
            (when-let [sq (seq sq)]
              (reduce-seq f (f acc (first sq)) (rest sq))))))
  ([f sq] (if-let [sq (seq sq)]
            (reduce-seq f (first sq) (rest sq))
            (list (f)))))

(test-reduce-seq reduce-seq)

;; And as a final flourish, I thought it would be nice to use the destructuring notation
(defn reduce-seq
  ([f acc sq]
     (cons acc
           (lazy-seq
            (when-let [[head & tail] (seq sq)]
              (reduce-seq f (f acc head) tail)))))
  ([f sq] (if-let [[head & tail] (seq sq)]
            (reduce-seq f head tail)
            (list (f)))))

(test-reduce-seq reduce-seq)

;; That works fine, but actually, the function look more 'noisy' like that than before,
;; so I prefer the penultimate version.

;; Feeling pretty happy with this, I thought about it for a bit, and decided that
;; "reductions" would be a better name for reduce-seq

;; So my final version was:
(defn reductions
  ([f acc sq]
     (cons acc
           (lazy-seq
            (when-let [sq (seq sq)]
              (reductions f (f acc (first sq)) (rest sq))))))
  ([f sq] (if-let [sq (seq sq)]
            (reductions f (first sq) (rest sq))
            (list (f)))))


"WARNING: reductions already refers to: #'clojure.core/reductions in namespace: user, being replaced by: #'user/reductions"

;; Here's the source of the standard version, which was apparently added in version 1.2:

(defn reductions
  "Returns a lazy seq of the intermediate values of the reduction (as
  per reduce) of coll by f, starting with init."
  {:added "1.2"}
  ([f coll]
     (lazy-seq
      (if-let [s (seq coll)]
        (reductions f (first s) (rest s))
        (list (f)))))
  ([f init coll]
     (cons init
           (lazy-seq
            (when-let [s (seq coll)]
              (reductions f (f init (first s)) (rest s)))))))

;; I suppose that there are some positives to take away from this:

;; At least I know that I am thinking along roughly the same lines as the designers
;; of Clojure....



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Footnote

;; Why doesn't this work any more?
;; (use 'clojure.contrib.trace)
;; (dotrace (reduce-seq) (take 5 (reduce-seq + 0 '(1 2 3 4 5))))

Sunday, September 5, 2010

Learn and Use the Standard Library

;; What a lot of ways there are to write frequencies!

(defn freq-merge [sq]
  (apply merge-with + (map (fn [c] {c 1}) sq)))

(defn freq-reduce-assoc [sq]
  (reduce #(assoc %1 %2 (inc (get %1 %2 0))) {} sq))

(defn freq-reduce-update [sq]
  (reduce #(update-in %1 [%2] (fnil inc 0)) {} sq))

(defn freq-loop [sq]
  (loop [acc {} sq sq]
    (if-let [sq (seq sq)]
      (recur (assoc acc (first sq) (inc (get acc (first sq) 0))) (rest sq))
      acc)))

;; Here's the source definition
(defn frequencies
  "Returns a map from distinct items in coll to the number of times
  they appear."
  {:added "1.2"}
  [coll]
  (persistent!
   (reduce (fn [counts x]
             (assoc! counts x (inc (get counts x 0))))
           (transient {}) coll)))

(def sq "abcdaabccc")
(time (frequencies sq))         "Elapsed time: 0.13 msecs"
(time (freq-loop sq))           "Elapsed time: 0.12 msecs"
(time (freq-reduce-assoc sq))   "Elapsed time: 0.13 msecs"
(time (freq-merge sq))          "Elapsed time: 0.20 msecs"
(time (freq-reduce-update sq))  "Elapsed time: 0.27 msecs"


(def sq (apply str (repeat 1000 "abcdaabccc")))
(time (frequencies sq))         "Elapsed time: 8  msecs"
(time (freq-loop sq))           "Elapsed time: 13 msecs"
(time (freq-reduce-assoc sq))   "Elapsed time: 13 msecs"
(time (freq-merge sq))          "Elapsed time: 42 msecs"
(time (freq-reduce-update sq))  "Elapsed time: 45 msecs"

(def sq (apply str (repeat 100000 "abcdaabccc")))
(time (frequencies sq))         "Elapsed time: 900  msecs"
(time (freq-loop sq))           "Elapsed time: 1500 msecs"
(time (freq-reduce-assoc sq))   "Elapsed time: 1500 msecs"
(time (freq-merge sq))          "Elapsed time: 5000 msecs"
(time (freq-reduce-update sq))  "Elapsed time: 5400 msecs"


;; Mumon's commentary: Learn and use the standard library

;; I don't know how many people read my ramblings, but if anyone notices places
;; where I could have used a library function, but have done it the hard way,
;; I'd consider it a great favour if you'd let me know.

Understanding RSA Public Key Encryption with Clojure

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; A Simple Explanation Of Public Key Encryption With Code

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; I'm no cryptographer! I've known about the RSA method for years, but as a rather
;; abstract piece of mathematics. On the basis that if you understand something, you
;; can program it, I sat down to try to explain it to myself this morning.

;; I hope the code might be useful to other people who get the heebie-jeebies
;; at the phrase "Euler's totient".

;; I'm completely avoiding proofs, but trying to explain how RSA works through
;; explaining how to implement it.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Caesar's Cipher

;; Julius Caesar encrypted his messages thus:

(def alphabet (take 26 (map char (iterate inc 0x61))))
(def shift 3)
(def permutation (concat (drop shift alphabet) (take shift alphabet)))
(def caesar-function (apply sorted-map (interleave alphabet permutation)))
(def caesar-inverse  (apply sorted-map (interleave permutation alphabet)))

;; To encrypt:
(apply str (map caesar-function "helloclassicalworld")) ;; "khoorfodvvlfdozruog"

;; To decrypt:
(apply str (map caesar-inverse  "khoorfodvvlfdozruog")) ;; "helloclassicalworld"

;; This cipher, whilst robust against the cryptanalytic talents of the
;; Transalpine Gauls, leaves something to be desired in a modern setting.

;; Of particular concern is the the need to communicate the cipher key (in this
;; case 3) secretly in some way prior to the sending of the message.

;; The key allows one to calculate both the encryption function and the
;; decryption function, as demonstrated above.

;; Caesar's generals would have met up early in the campaign to discuss the
;; cipher they were going to use.

;; Caesar's cipher allows us to see certain basic principles of encryption.

;; All information can be treated as sequences of numbers.  The numbers can be
;; obscured by applying a function to them.

;; To read an encrypted message, calculate the inverse function, and apply it to
;; the message.

;; The problem with Caesar's cipher, and other more modern ciphers like it, is
;; that by telling someone the encryption function, you've also told them the
;; decryption function.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; In 1970, a method was invented that allowed people to communicate the
;; encryption function without giving away the decryption function.

;; It turns out that powers of numbers modulo other numbers are very easy to
;; calculate even by hand. Here's a method that is fast.

(defn square [n] (* n n))

(defn power-modulo [a n m]
  (mod (cond
        (= n 0) 1
        (= n 1) a
        (odd? n) (* a (power-modulo a (dec n) m))
        :else (square (power-modulo a (/ n 2) m)))
       m))

;; It doesn't take many steps to calculate 7^5 mod 247 
(power-modulo 7 5 247) ;; 11
;; But neither does it take many step to calculate 11^29 mod 247
(power-modulo 11 29 247) ;; 7
;; Or 243^229 mod 247
(power-modulo 243 229 247) ;; 48

;; If we fix n and m, then we can make a function very like Caesar's encryption function:
(defn make-cipher[n m] (fn[a] (power-modulo a n m)))

(def cipher-5-247 (make-cipher 5 247))

;; So we could use x -> x^5 mod 247 in the same way as Caesar:
(def encrypted-message (map cipher-5-247 (map int "hellomodernworld")))
;; (130 43 166 166 232 200 232 237 43 95 2 123 232 95 166 237)

;; But what on earth is the inverse function to get the message back?

;; Well, as it happens, it's another, similar function.
;; Something like (make-cipher b 247) where the problem is to find b

;; We can crack this problem fairly easily:
;; If we guess at b, what will the combination of ciphering and unciphering look like?
(defn cipher-uncipher [b]
  (fn [x] ((make-cipher b 247) (cipher-5-247 x))))

;; This function takes a range of bs, and tries to encrypt and decrypt the single
;; number x, to see if it comes back to itself. It throws away any potential bs
;; where this doesn't happen
(defn sieve [rnge x]
  (filter #(= ((cipher-uncipher %) x) x) rnge))

;; Let's try all b from 0 to 247
(sieve (range 247) 1) ;;Irritatingly 1 always comes back to 1
;; But we get luckier with 2. 2 only comes back to 2 with a few bs in our range.
(sieve (sieve (range 247) 1) 2) ;; (29 65 101 137 173 209 245)

;; Let's try 29

(def cipher-29-247 (make-cipher 29 247))
(apply str (map char (map cipher-29-247 encrypted-message)))
;; And we appear to have found our decryption method!

;; Let's just check that cipher-29-247 and cipher 5-247 really are inverses.
(= (map cipher-29-247 (map cipher-5-247 (range 247)))
   (range 247))

;; Now the thing is, although it can be done, there's quite a lot of computation
;; involved in finding the inverse cipher.

;; It's not at all obvious that power 5 is the inverse of power 29 in arithmetic mod 247
;; Even though we can work it out by trying loads of alternatives.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; But actually, if you can factorize 247, it's easy to calculate inverse
;; functions for powers mod 247

;; 247 is (* 13 19), and using that, we can calculate a magic number

(def magic-number-for-247 (* (dec 13) (dec 19))) ;;216

;; We can find a number which is inverse to 5 modulo the magic-number
(filter #(= 1 (mod (* 5 %) magic-number-for-247)) (range 247)) ;; 173

;; Check that 173 is inverse to 5 mod 216
(mod (* 5 173) 216) ;; 1

;; And that proves that cipher-173-247 is inverse to cipher-5-247. Let's try it.
(def cipher-173-247 (make-cipher 173 247))

(=
 (range 247)
 (map (comp cipher-173-247 cipher-5-247) (range 247))) ;; true

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Now, (make-cipher 5 247) is not a very strong method of encryption.

;; But if we can find larger prime numbers to use, then we can make better ciphers.

;; Getting a couple of large primes is easy:
;; Here's a way to get some four-digit ones
;; (require 'clojure.contrib.lazy-seqs)
;; (take 2 (drop 1000 clojure.contrib.lazy-seqs/primes))

;; Let's take 7927 and 7933. Again, they're not nearly large enough to be practically
;; useful, but they are large enough to make easy cracks more difficult.

;; Multiply them to get the modulus for the cipher
(def modulus (* 7927 7933)) ;; 62884891

;; We just choose an encrypting power at random, say 203
(def encipher (make-cipher 203 modulus))

;; Calculating the magic number is easy:
(def magic-number (* (dec 7927) (dec 7933))) ;; 62869032

;; Now to find the inverse function, we need a number a such that (* a 203) = 1 mod 62869032
;; These are easy to find
(take 3 (filter #(= (int %) %) (map #(/ % 203) (iterate #(+ % magic-number) 1)))) ;;(929099 63798131 126667163 .....)
;; Let's take the first one

;; Check that it does what we want:
(mod (* 203 929099) 62869032) ;; 1

;; Now we can create the deciphering function:
(def decipher (make-cipher 929099 modulus))
;; Now, notice that it has taken almost no computational power to create this cipher.
;; You could do this easily by hand.

;; Encryption and decryption would be hard by hand, but possible due to the extreme efficiency of the
;; algorithm in the power-modulo function.

;; With a computer, it is easy:
(def secret-message (map encipher (map int "darling world, we must meet soon...")))
;; (48146327 60382173 57991209 5919317 9620507 44143496 27738744 52452577
;; 2896855 2177970 57991209 5919317 48146327 54215221 52452577 2896855 8841709
;; 52452577 38496398 16747575 44075818 60012204 52452577 38496398 8841709
;; 8841709 60012204 52452577 44075818 2177970 2177970 44143496 37504468 37504468
;; 37504468)

(map decipher secret-message)
;; (100 97 114 108 105 110 103 32 119 111 114 108 100 44 32 119 101 32 109 117
;; 115 116 32 109 101 101 116 32 115 111 111 110 46 46 46)

(apply str (map char (map decipher secret-message)))
;;"darling world, we must meet soon..."

;; But just verifying that the cipher works over its whole range 62884891 is time consuming
(def test-cipher (comp decipher encipher))

(time (= (range 1000) (map test-cipher (range 1000))))
"Elapsed time: 115.158749 msecs"
;; The time to check the whole thing would be about 10 minutes!
;; It would be utterly impossible by hand.

;; The cracking methods also suffer:
(defn cipher-uncipher [b]
  (fn [x] ((make-cipher b modulus) (encipher x))))

(defn sieve [rnge x]
  (filter #(= ((cipher-uncipher %) x) x) rnge))

(time (doall (sieve (sieve (range 10000) 1) 2))) ;;()
"Elapsed time: 1246.92162 msecs"

;; In one second, we have checked 10000 possibilities and not found an answer

;; If we were to sieve a much larger range, we would find an answer, but it would take ages
;; even by computer

;; (time (doall (sieve (sieve (range 1000000) 1) 2)))
;; "Elapsed time: 170559.809623 msecs"
;; (929099)

;; It does work eventually, but it would have been a lot easier to factorize
;; 62884891 and then work out the inverse in the same way that the generator did.

;; Finding very large prime numbers is very easy. Factorising their products is very hard.

;; If we choose gigantic primes then the only methods known of finding the
;; inverse functions involve factorising very large numbers which are the
;; products of two very large primes.

;; This is thought to be computationally infeasible once the number of digits in the primes
;; goes above about 1000.

;; This is the basis of public key encryption.  It is very easy to create these
;; ciphers, fairly easy to use them to encrypt, and very very hard indeed to
;; invert them.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Footnotes


;; This algorithm was discovered by Clifford Cocks, a mathematician working for
;; British Intelligence in 1973.

;; However, in 1973 it would not have been terribly practical to use on the
;; hardware of the time and his work was considered a curiosity by the agency.

;; It was nevertheless classified top secret, preventing him from publishing the
;; scheme.

;; It was independently discovered by Rivest, Shamir, and Adleman at MIT in
;; 1978, and is today universally known as the RSA algorithm.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; We've left a big hole in our encryption method!

;; So long as we're only enciphering the ASCII codes directly, we don't actually
;; need to invert the cipher. Just a lookup table of known characters will do.

(def sneaky (apply sorted-map (interleave
                               (map encipher (map int alphabet))
                               (map int alphabet))))

(apply str (map char (filter #(not (nil? %))
                             (map sneaky
                                  '(48146327 60382173 57991209 5919317 9620507
                                             44143496 27738744 52452577 2896855
                                             2177970 57991209 5919317 48146327 54215221
                                             52452577 2896855 8841709 52452577 38496398
                                             16747575 44075818 60012204 52452577 38496398
                                             8841709 8841709 60012204 52452577
                                             44075818 2177970 2177970 44143496)))))
;;"darlingworldwemustmeetsoon"

;; And of course this will be a problem with any method where the encryption
;; algorithm is publically known.

;; But if we were using the whole range 0-62884891, then this lookup table would
;; need to be extremely large, and take a long time to generate. Again, it would
;; just be easier to factorize the modulus and calculate the inverse.

;; We must ensure we're using the whole range by compressing the data before
;; encrypting it.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Even with compression, RSA is dubious as method for transmitting
;; messages. It's quite slow for the sorts of very large primes used in
;; practice, and it's vulnerable to various known plaintext attacks,
;; chosen-ciphertext attacks, etc.

;; However, it's perfect for swapping cipher keys for other forms of encryption.

;; This means that two people who have no opportunity to communicate securely
;; with each other can securely swap cipher keys, and from then on, they can use
;; a better suited coding method to communicate securely.

;; Something from nothing!

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The security of RSA rests on the problem of factoring large numbers, which is thought to be
;; very difficult for a classical computer.

;; However, it is known to be very easy for a quantum computer, using Shor's algorithm.
;; Quantum computation is in its infancy, but a quantum computer has been built which 
;; used Shor's algorithm to factor the number fifteen.

;; If it turns out that quantum computers capable of handling 1000 digit numbers can be built,
;; then RSA will be blown wide open.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; I seem to have found a way to blow stack

(reduce sieve '(929099) (range 1 1000)) ;;fails

(reduce sieve '(929099) (range 1 250)) ;; all work individually
(reduce sieve '(929099) (range 250 500))
(reduce sieve '(929099) (range 500 750))
(reduce sieve '(929099) (range 750 1000))

;; I don't understand why this should be happening.

Tuesday, August 24, 2010

SLIME debugger

http://hugoduncan.org/post/2010/swank_clojure_gets_a_break_with_the_local_environment.xhtml

;; All power to:

;; http://hugoduncan.org/post/2010/swank_clojure_gets_a_break_with_the_local_environment.xhtml

;; Who has given us a way to debug things under emacs/slime/swank, by stopping a
;; running program to examine the variables

;; First define this function under emacs/slime/swank

(defn factorial [n]
  (when (= n 23) (swank.core/break))
        (if (< n 2) n
            (* n (factorial (dec n)))))


;; Then try 
(factorial 30)
;; at the repl, so it runs in the repl thread, rather than executing it with
;; C-M-x or C-x e, which for some reason doesn't work as well.

;; Hugo's article explains how to view the local environment and create a repl
;; in context so that you can examine the state of the program when break was
;; called. You can then restart as if nothing had happened.

;; It's not as wonderful as traditional SLIME/LISP debugging, but it's a good 
;; start!


Followers