Hi all,

in my quest to learn clojure (and lisp in general), I'm currently
trying to translate some the "On Lisp" code to clojure.

The first couple of functions and macros in Chapter 19 "A Query
Compiler" read:

(defun make-db (&optional (size 100))
  (make-hash-table :size size))

(defvar *default-db* (make-db))

(defun clear-db (&optional (db *default-db*))
  (clrhash db))

(defmacro db-query (key &optional (db '*default-db*))
  `(gethash ,key ,db))

(defun db-push (key val &optional (db *default-db*))
  (push val (db-query key db)))

(defmacro fact (pred &rest args)
  `(progn (db-push ',pred ',args)
          ',args))

My clojure version of it:

(def make-db hash-map)

(def *default-db* (atom (make-db)))

(defn clear-db
  ([] (clear-db *default-db*))
  ([db]
     (swap! db (fn [_] (make-db)))))

(defn db-query
  ([k] (db-query k *default-db*))
  ([k db]
     (@db k)))

(defn db-push
  ([key val] (db-push key val *default-db*))
  ([key val db]
     (swap! db (fn [db]
                 (assoc db key (cons val (db key)))))))

(defmacro fact
  [pred & args]
  `(do
     (db-push '~pred '~args)
     '~args))

The code works fine:

(clear-db)
(fact painter hogarth william english)
(fact painter canale antonio venetian)
(fact painter reynolds joshua english)
(fact dates hogarth 1697 1772)
(fact dates canale 1697 1768)
(fact dates reynolds 1723 1792)

user=> (db-query 'painter)
((reynolds joshua english) (canale antonio venetian) (hogarth william
english))
user=> (db-query 'dates)
((reynolds 1723 1792) (canale 1697 1768) (hogarth 1697 1772))

However, there are a couple of things I'm not sure about:

* Is "function overloading" the idiomatic way to implement default
params in clojure?
* I'm using an atom to store the database. Could I use a var instead?
I don't see how though.
* Can the body of the db-push function be simplified?

Thanks, R.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to