Skip to content

Instantly share code, notes, and snippets.

View ponzao's full-sized avatar

Vesa Marttila ponzao

  • Helsinki, Finland
View GitHub Profile
@ponzao
ponzao / tictactoe.clj
Last active December 22, 2015 14:19
Declarative (= bloated) Tic-Tac-Toe solver in Clojure and core.logic.
(defn solve
[grid]
(remove nil?
(run* [q]
(macro/symbol-macrolet [_ (lvar)]
(== q grid)
(conde
((== grid [[q _ _]
[_ q _]
[_ _ q]]))
@ponzao
ponzao / coder.clj
Last active December 20, 2015 07:49
Martin Odersky's Phone Coder example translated into Clojure
(use '[clojure.string :only (join)])
(defn coder
[dictionary]
(let [mnemonics {\2 "ABC" \3 "DEF" \4 "GHI" \5 "JKL",
\6 "MNO" \7 "PQRS" \8 "TUV" \9 "WXYZ"}
char-code (into {} (mapcat (fn [[n cs]]
(map #(vector % n) cs))
mnemonics))
let rec cycle xs =
Seq.concat (Seq.initInfinite (fun _ -> xs))
(ns core
(:use quil.core))
(defn tick
[state]
(let [neighbors (fn [x y]
(for [xinc (range -1 (inc 1))
yinc (range -1 (inc 1)) :when (not (= 0 xinc yinc))]
[(+ x xinc) (+ y yinc)]))
map-matrix (fn [f matrix]
;; without numbers
(def fizzbuzz
(let [fizz (cycle [nil nil "fizz"])
buzz (cycle [nil nil nil nil "buzz"])]
(remove empty? (map str fizz buzz))))
;; with numbers
(defn fizzbuzz
[n]
(let [xs (range 1 (inc n))
(require 'clojure.set)
(def connections
["3-4"
"4-9"
"8-0"
"2-3"
"5-6"
"2-9"
"5-9"
(def dictionary
(with-open [rdr (reader "/usr/share/dict/words")]
(conj (set (line-seq rdr)) "clojure")))
(defn correctly-spelled?
[sentence]
(->> (.toLowerCase sentence)
(re-seq #"\w+")
(every? dictionary)))
;; Gathers values up to (and including) the one for
;; which the predicate fails.
(defn take-to
[pred coll]
(when-let [s (seq coll)]
(let [[x & xs] s]
(if-not (pred x)
(list x)
(lazy-cat (cons x (take-to pred xs)))))))
class C { def b = "b" }
trait T extends C { override def b = "trait b" }
val c = new C with T
c.b // => java.lang.String = trait b
(defn- in-transaction [f]
(try
(do (println "starting...")
(let [rv (f)]
(println "commiting...")
rv))
(catch Exception e
(println "rollbacking..."))))
(defmacro transactional [expr]