Tuesday, January 03, 2012

Vocabulary trainer in Clojure

~/src/gh/voc/train.clj.html
(use '[clojure.string :only (split split-lines)])

; file is tab-seperated pairs of foreign and native words

(let [contents (slurp "100a.txt" :encoding "utf-8")
      lines (split-lines contents)
      pairs (map #(split % #"\t") lines)]

  (loop [my-pairs (shuffle pairs)]
    (let [pair (first my-pairs)]
      (do
        (println)
        (println (first (first my-pairs)))
        (if (not= (read-line) (second pair))
          (do
            (println "wrong, correct is:" (second pair))
            (recur (shuffle my-pairs)))
          (do
            (println "correct")
            (if (seq (rest my-pairs)) ; (seq idiomatic for (not (empty?
              (recur (rest my-pairs)))))))))

Monday, January 02, 2012

Monty Hall problem in Clojure

~/src/gh/goat.clj.html
; Monty Hall problem in Clojure

(defn pick-first-guess [doors]
  (first doors)
)

(defn change-guess [doors]
  (if (= :goat (second doors)) (last doors)
    (second doors))
)

(def samples (map shuffle (repeat 1000 [:goat :goat :car])))

(count (filter #(= % :car) (map pick-first-guess samples)))
(count (filter #(= % :car) (map change-guess samples)))