Anyway, i take no credit for the generate-prime function. It was a port (and it's an ugly one) of javascript code found here
Code: Select all
(defn generate-prime
[] ;; a higher order function
(letfn [(sieve [a b] ;; a is a map of numbers, b is a number
(loop [X a Y b]
(if (nil? (get X Y))
(cons Y (lazy-seq
(sieve
;; javascript array is a persistent version of a transient collection
;; hence the use of 'persistent!' and 'transient'
(persistent! (assoc!
(transient X)
(* Y Y) (list Y))) (inc Y))))
(let [factors-of-Y (get X Y)
kv (mapcat
list
(map #(+ % Y) factors-of-Y)
(map #(cons % (get X (+ % Y) (list)))
factors-of-Y))]
(recur (persistent!
(dissoc!
(apply assoc! (transient X) kv) Y))
(inc Y))))))]
(sieve {} 2))) ;; a is initialized as empty map, b is set to two since the lowest prime is two
Code: Select all
(defn string->primes [s]
(for [i (range (count s))]
(let [print-prime #(printf "found %s, add %d \n" (get s i) (nth (generate-prime) %))
charify-s (get s i)]
(cond
(or (= charify-s \a) (= charify-s \A)) (print-prime 0)
(or (= charify-s \b) (= charify-s \B)) (print-prime 1)
(or (= charify-s \c) (= charify-s \C)) (print-prime 2)
(or (= charify-s \d) (= charify-s \D)) (print-prime 3)
(or (= charify-s \e) (= charify-s \E)) (print-prime 4)
(or (= charify-s \f) (= charify-s \F)) (print-prime 5)
(or (= charify-s \g) (= charify-s \G)) (print-prime 6)
(or (= charify-s \h) (= charify-s \H)) (print-prime 7)
(or (= charify-s \i) (= charify-s \I)) (print-prime 8)
.. ;; keep going until char \9))))
Code: Select all
(string->prime ("aBHbA")
;=>
found a, add 2
found B, add 3
found H, add 19
found b, add 3
found A, add 2
@Gekko: This too was beyond my programming skill, it took quite a lot of trials and errors (meaning hours) and C-c C-d g on the CIDER repl like everytime.
@Pidsley: though i don't quite understand Haskell, your code looks beautiful