;; 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))))
Search This Blog
Monday, September 6, 2010
reduce-seq: An Exercise in Laziness and Futility
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!
Reduce: Not Scary
;; Three very fundamental operators in any sort of programming are map, filter ;; and reduce. ;; They represent the common programming tasks of transforming a collection, ;; selecting from it, and summing over it. ;; Most people think that map and filter are fairly obvious, but there seems to ;; be a certain amount of confusion about reduce. ;; But it's actually very simple in concept, and represents an easy idea. ;; Often one needs to loop over a collection, and store results in an ;; accumulator. ;; The simplest example of a reduction would be adding the numbers in a list. ;; Suppose the numbers are 1,2,3,4,5,6,7,8,9,10 and we want to find their sum ;; In C, or another naturally imperative language, we'd say: ;; int list[]={1,2,3,4,5,6,7,8,9,10}; ;; int len=10; ;; int a=0; ;; int i; ;; for (i=0; i<len; i++){ ;; a += list[i]; ;; } ;; Using atoms to provide mutable state, we can do something similar in Clojure: (def lst '(1 2 3 4 5 6 7 8 9 10)) (def len 10) (def a (atom 0)) (dotimes [i len] (swap! a + (nth lst i))) ;; The value ends up in the atom a, just as in the C version. ;; In clojure, this looks slightly more complicated. ;; Partly because mutation in clojure is intrinsically more complicated, because ;; clojure is extremely concerned with thread safety, and so we need to allocate ;; and dereference atoms rather than mutating local variables. ;; And partly because C has very good notations for its fundamental operations. ;; But logically they're the same algorithm. ;; But I'd feel dirty writing this code in clojure, even though that would have ;; been a perfectly good piece of LISP in the sixties. It's just a feeling that ;; I have that it is better to avoid mutation unless it's actually necessary. ;; Even though the mutation-less algorithms are often harder to write, they're ;; often easier to debug and test. ;; A more natural way to accumulate over a list in clojure is the ;; loop-as-function-call, with accumulator and iterator as parameters: (loop [a 0 i 0] (if (= i len) a (recur (+ a (nth lst i)) (inc i)))) ;; This is much more idiomatic code in clojure, and it doesn't mutate any values ;; even though the variable-rebinding in the recur call produces a very similar ;; effect. ;; And here the final value is the value of the expression, which is nicer. ;; Of course, clojure's lists know when they are empty, so we don't need an ;; explicit loop counter. ;; So how about: (loop [a 0 l lst] (if (empty? l) a (recur (+ a (first l)) (rest l)))) ;; l moves along the list, while a accumulates the values. ;; It still looks a bit long-winded, but we can easily imagine that this is a ;; common pattern: (loop [a _ l _] (if (empty? l) a (recur (_ a (first l)) (rest l)))) ;; Where the blanks represent holes in the boilerplate we have to fill in. ;; It should be almost as common as the equivalent pattern: ;; a= _ ;; for(i=0; i<_; i++) ;; { ;; a _= _ [i] ;; } ;; is in C. ;; Where in both cases we need to fill in the _ with the initial value of the ;; accumulator, the list to be accumulated over, and the operation to be ;; performed. ;; Pretty much the first law of programming is: ;; If you see a common pattern, you should name it and abstract it so it goes away. ;; The pattern is called reduce. ;; We need to fill in the blanks with the function to do the accumulating, ;; the initial value of the accumulator, and the list ;; Since we're reducing the list lst, using the operation +, and starting ;; with the value zero, we write: (reduce + 0 lst) ;; reduce is clojure's natural way of expressing accumulation over a list ;; in the same way as the for-loop over += and ++ is C's ;; Here are some other examples (reduce * 1 lst) ;; We use * instead of +, and start with 1 instead of 0 ;; This produces the product of the numbers in the list. ;; In these cases where the order of the arguments doesn't matter ;; we can think of reduce as 'put the function between the values' (reduce + 0 '(1 2 3 4 5 6 7 8 9 10)) ; (0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) (reduce * 1 '(1 2 3 4 5 6 7 8 9 10)) ; (1 * 1 * 2 * 3 * 4 * 5 * ........) ;; But this image is actually harmful when the ordering does matter. ;; What's really going on is that the operator is being used to feed values ;; into the accumulator one by one. (reduce + 0 '(1 2 3)) ;; proceeds like: ;; (+ 0 1) -> 1 ;; (+ 1 2) -> 3 ;; (+ 3 3) -> 6 ;; If this seems confusing, even though you're happy with the C version, ;; think about the C loop. ;; They're actually just different ways of expressing the same idea, ;; and should look equally natural. Seeing how either one can always be ;; transformed into the other will help. ;; Here's an example where the order does matter: (reduce conj '() '(1 2 3)) ;; How do we think about this? (conj '() 1) ; -> '(1) (conj '(1) 2) ; -> '(2 1) (conj '(2 1) 3) ; -> '(3 2 1) ;; So (reduce conj '() '(1 2 3)) -> '(3 2 1) ;; Of course this simple reduction is so common that the pattern ;; (reduce conj '() _ ) already has a name (reverse '( 1 2 3 )) ;; Here's the definition of reverse in the clojure.core source code! (defn reverse "Returns a seq of the items in coll in reverse order. Not lazy." {:added "1.0"} [coll] (reduce conj () coll)) ;; An acceptable definition of reduce itself would be: (defn my-reduce [fn init coll] (loop [acc init l (seq coll)] (if (empty? l) acc (recur (fn acc (first l)) (rest l))))) ;; This works on any collection that can be made into a sequence: (my-reduce * 1 '(1 2 3)) ;; a list (my-reduce * 1 #{1,2,3}) ;; a set (my-reduce * 1 [1,2,3]) ;; a vector ;; The real reduce in clojure.core is an optimised version and can deal with all ;; sorts of collections efficiently, but in spirit it is just making every ;; collection into a sequence and then doing what my little skeleton above did. ;; It also has another feature, which is that if you don't provide an initial ;; value for the accumulator, then it takes the first element of the sequence as ;; its initial value, and accumulates over the rest of the sequence. ;; For operations which produce answers of the same type as their arguments, ;; this is often what you want. (reduce * '(1 2 3 4)) ;24 (reduce + [1 2 3 4]) ;10 (reduce bit-xor '(1 2 3 4 5)) ;1 ;; So why has this simple operation got a scary reputation? ;; I think it's because all the common cases are so useful that they have ;; already been further abstracted away, like reverse. So in fact you don't ;; meet it that often in practice. ;; Let's see if we can construct something more interesting: ;; Suppose you had a list of strings (def strlist '("fred" "barney" "fred" "wilma")) ;; And wanted to count how many times each string occurs in the list. ;; We want an accumulator to keep the strings and counts in, and a function ;; which will take that accumulator, and a new string, and return the updated ;; accumulator. ;; The obvious accumulator is a map. We'd want the answer to be something like {"fred" 2, "barney" 1, "wilma" 1} ;; So what function will add strings to a map? ;;In a rather naive and long-winded way: (defn addtomap [map string] (let [oldval (if (contains? map string) (map string) 0)] (assoc map string (inc oldval)))) ;; Here's how we'd use it to count our list, starting from the empty map {}, and ;; using addtomap to add each string into the accumulator returned by each call. (addtomap {} "fred") ;; {"fred" 1} (addtomap {"fred" 1} "barney") ;; {"barney" 1, "fred" 1} (addtomap {"fred" 1, "barney" 1} "fred") ;; {"fred" 2, "barney" 1} (addtomap {"fred" 2, "barney" 1} "wilma") ;; {"wilma" 1, "fred" 2, "barney" 1} ;; So the reduce part is obvious, once you have addtomap (reduce addtomap {} strlist) ;; But a real Clojure programmer would look at addtomap and think: ;; We can write (map string 0) instead of ;; (if (contains? map string) ;; (map string) ;; 0) ;; So a better version of addtomap would be: (defn addtomap [map string] (let [oldval (map string 0)] (assoc map string (inc oldval)))) (reduce addtomap {} strlist) ;; And now the let statement looks redundant, so let's say (defn addtomap [map string] (assoc map string (inc (map string 0)))) (reduce addtomap {} strlist) ;; And then he might say ;; "since I'm only going to use this function here, why not make it anonymous?" (fn [map string] (assoc map string (inc (map string 0)))) ;; And now the reduce looks like: (reduce (fn [map string] (assoc map string (inc (map string 0)))) {} strlist) ;; And, well, at this point, any reasonable man is going to think: ;; "Since I'm writing a one-liner, I might as well use the anonymous shorthand" #(assoc %1 %2 (inc (%1 %2 0))) (reduce #(assoc %1 %2 (inc (%1 %2 0))) {} strlist) ;; And if you already understand reduce and anonymous functions, and how maps ;; work, this is actually not too hard to understand. ;; In fact this is the version of the function that I originally wrote. ;; But I can see it might be a bit off-putting if you thought reduce itself was ;; scary. ;; Actually the obfuscation / pleasing terseness is all in the anonymous ;; function, and the behaviour of maps, and the reduce bit isn't scary at all. ;; Here's another deliberately obscure example, using a little structure as an ;; accumulator. See if you can figure out what it does using the above ideas to ;; unpack it. I'm using the destructuring notation to take the little structure ;; apart, and then the function modifies each part and puts them back together again (reduce (fn[[c s] n] [(+ c n), (str s n)]) [0,""] lst) ;; The trick is to work out what the anonymous function does to the starting ;; value of the accumulator when it gets a value from the list. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Clojure's natural facility with abstractions and small functions allows ;; some truly terse code. ;; This little piece of code counts words in a file and orders them by popularity: (sort #(< (%1 1) (%2 1)) (reduce #(assoc %1 %2 (inc (%1 %2 0))) {} (clojure.contrib.string/split #"\W" (slurp "/home/john/hobby-code/reduce.clj")))) ;; With practice this sort of thing is actually readable. Promise! ;; But if I was actually writing it for someone else to read, ;; I'd probably split it up and give the bits names. (let [filecontents (slurp "/home/john/hobby-code/reduce.clj") words (clojure.contrib.string/split #"\W" filecontents) wordmap (reduce #(assoc %1 %2 (inc (%1 %2 0))) {} words) sortedwords (sort #(< (%1 1) (%2 1)) wordmap)] sortedwords) ;; And if I knew the library, I'd remember that two of those little operations ;; actually already have names: ;; The idiom ( reduce #(assoc %1 %2 (inc (%1 %2 0)) {} .... ) ;; which I used to find myself writing all the time, is such a useful thing ;; that it too has made it into clojure.core as the function frequencies: (frequencies strlist) ;; and the sort with the comparator on the second elements can be replaced by sort-by, and second (let [filecontents (slurp "/home/john/hobby-code/reduce.clj") words (clojure.contrib.string/split #"\W" filecontents) wordmap (frequencies words) sortedwords (sort-by second wordmap)] sortedwords) ;; And then I'd abstract away the word counting operations from the file reading part (defn sorted-word-frequencies [string] (sort-by second (frequencies (clojure.contrib.string/split #"\W+" string)))) ;; So now I can ask for the 10 most popular words: (take 10 (reverse (sorted-word-frequencies (slurp "/home/john/hobby-code/reduce.clj")))) ;; which is also pleasingly terse, but I think more readable.
Wednesday, August 18, 2010
A Special Squarish Age
Microsoft Research published some problems for their 15th anniversary, some of which are quite tricky.
This one isn't, but I liked the program I wrote to solve it because it demonstrates how nice lazy streams are.
This one isn't, but I liked the program I wrote to solve it because it demonstrates how nice lazy streams are.
;; Microsoft Research 15th Anniversary Problem: A special squarish age. ;; A number is squarish if it is the product of two consecutive integers. ;; e.g. 6 is squarish because it is the product of 2 and 3 ;; A colleague claims that his age is squarish, and furthermore, that his last squarish birthday was a squarish number of years ago. ;; What age could he be? (def squarish (map (fn[[x y]] (* x y)) (partition 2 1 (iterate inc 0)))) (def squarishdiffs (map - (drop 1 squarish) squarish)) (defn find-in-increasing-seq [x seq] (cond (empty? seq) false (< (first seq) x) (recur x (rest seq)) (= (first seq) x) true (> (first seq) x) false)) (defn squarish? [x] (find-in-increasing-seq x squarish)) (def possible-ages (mapcat (fn [s d] (if (squarish? d) (list s) '())) (drop 1 squarish) squarishdiffs)) (take 10 possible-ages) ;; He's probably 42. 12 is a bit young for a colleague, 110 is pushing it.
Subscribe to:
Posts (Atom)
