comparison src/clojure/contrib/datalog/util.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
comparison
equal deleted inserted replaced
9:35cf337adfcf 10:ef7dbbd6452c
1 ;; Copyright (c) Jeffrey Straszheim. All rights reserved. The use and
2 ;; distribution terms for this software are covered by the Eclipse Public
3 ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
4 ;; be found in the file epl-v10.html at the root of this distribution. By
5 ;; using this software in any fashion, you are agreeing to be bound by the
6 ;; terms of this license. You must not remove this notice, or any other,
7 ;; from this software.
8 ;;
9 ;; util.clj
10 ;;
11 ;; A Clojure implementation of Datalog -- Utilities
12 ;;
13 ;; straszheimjeffrey (gmail)
14 ;; Created 3 Feburary 2009
15
16
17 (ns clojure.contrib.datalog.util
18 (:use [clojure.contrib.seq :only (separate)]))
19
20
21
22 ;;; Bindings and logic vars. A binding in a hash of logic vars to
23 ;;; bound values. Logic vars are any symbol prefixed with a \?.
24
25 (defn is-var?
26 "Is this a logic variable: e.g. a symbol prefixed with a ?"
27 [sym]
28 (when (symbol? sym)
29 (let [name (name sym)]
30 (and (= \? (first name))
31 (not= \? (fnext name))))))
32
33 (defn is-query-var?
34 "Is this a query variable: e.g. a symbol prefixed with ??"
35 [sym]
36 (when (symbol? sym)
37 (let [name (name sym)]
38 (and (= \? (first name))
39 (= \? (fnext name))))))
40
41 (defn map-values
42 "Like map, but works over the values of a hash map"
43 [f hash]
44 (let [key-vals (map (fn [[key val]] [key (f val)]) hash)]
45 (if (seq key-vals)
46 (apply conj (empty hash) key-vals)
47 hash)))
48
49 (defn keys-to-vals
50 "Given a map and a collection of keys, return the collection of vals"
51 [m ks]
52 (vals (select-keys m ks)))
53
54 (defn reverse-map
55 "Reverse the keys/values of a map"
56 [m]
57 (into {} (map (fn [[k v]] [v k]) m)))
58
59
60 ;;; Preduce -- A parallel reduce over hashes
61
62 (defn preduce
63 "Similar to merge-with, but the contents of each key are merged in
64 parallel using f.
65
66 f - a function of 2 arguments.
67 data - a collection of hashes."
68 [f data]
69 (let [data-1 (map (fn [h] (map-values #(list %) h)) data)
70 merged (doall (apply merge-with concat data-1))
71 ; Groups w/ multiple elements are identified for parallel processing
72 [complex simple] (separate (fn [[key vals]] (> (count vals) 1)) merged)
73 fold-group (fn [[key vals]] {key (reduce f vals)})
74 fix-single (fn [[key [val]]] [key val])]
75 (apply merge (concat (pmap fold-group merged) (map fix-single simple)))))
76
77
78 ;;; Debuging and Tracing
79
80 (def *trace-datalog* nil)
81
82 (defmacro trace-datalog
83 "If *test-datalog* is set to true, run the enclosed commands"
84 [& body]
85 `(when *trace-datalog*
86 ~@body))
87
88
89 ;; End of file