First time using DataScript

156 views
Skip to first unread message

Alan Thompson

unread,
Sep 26, 2016, 8:38:29ā€ÆPM9/26/16
to clo...@googlegroups.com
Hi - I was answering a question on StackOverflow, and after solving it using functions from clojure.core, I thought it was the Ā prefect candidate for a little DataScript.Ā  Basically the user wants to do a "natural join" on column :obs/A, then print out pairs of :obs/value from type :x and type :y.Ā  The DataScript version removes a lot of tedious, manual indexing, filtering, unification, etc.


(ns clj.core
Ā  (:require [tupelo.core :as t]Ā 
Ā  Ā  Ā  Ā  Ā  Ā  [datascript.core :as d]
Ā  Ā  Ā  Ā  Ā  Ā  [clojure.set :as set] ))
(t/refer-tupelo)

(def data
Ā  [ {:type :x :local/id 1, Ā  :obs/A "11", Ā  Ā :obs/value 2.0, Ā  Ā :obs/color "yellow"}
Ā  Ā  {:type :x :local/id 2, Ā  :obs/A "12", Ā  Ā :obs/value 4.0, Ā  Ā :obs/color "blue"}
Ā  Ā  {:type :x :local/id 3, Ā  :obs/A "13", Ā  Ā :obs/value 3.0, Ā  Ā :obs/color "green"}
Ā  Ā  {:type :x :local/id 3, Ā  :obs/A "15", Ā  Ā :obs/value 7.0, Ā  Ā :obs/color "red"}Ā 

Ā  Ā  {:type :y :local/id 2, Ā  :obs/A "11", Ā  Ā :obs/value 7.0, Ā  Ā :obs/shape "square"}
Ā  Ā  {:type :y :local/id 2, Ā  :obs/A "13", Ā  Ā :obs/value 4.0, Ā  Ā :obs/shape "circle"}
Ā  Ā  {:type :y :local/id 6, Ā  :obs/A "15", Ā  Ā :obs/value 3.0, Ā  Ā :obs/shape "triangle"} ] )

(newline) (println "data") (pretty data)

(def conn (d/create-conn {}))
(d/transact! conn data)

(def labelled-result
Ā  (d/q '[:find ?a ?value1 ?value2
Ā  Ā  Ā  Ā  Ā  Ā  Ā :whereĀ 
Ā  Ā  Ā  Ā  Ā  Ā  Ā  Ā [?ex :type :x] [?ex :obs/A ?a] [?ex :obs/value ?value1]
Ā  Ā  Ā  Ā  Ā  Ā  Ā  Ā [?ey :type :y] [?ey :obs/A ?a] [?ey :obs/value ?value2]
Ā  Ā  Ā  Ā  Ā  Ā  ] @conn ))
(newline) (println "labelled-result") (pretty labelled-result)

(defn -main [& args] )

ā€‹With the result:

ā€‹

data
[{:type :x,
Ā  :local/id 1,
Ā  :obs/A "11",
Ā  :obs/value 2.0,
Ā  :obs/color "yellow"}
Ā {:type :x,
Ā  :local/id 2,
Ā  :obs/A "12",
Ā  :obs/value 4.0,
Ā  :obs/color "blue"}
Ā {:type :x,
Ā  :local/id 3,
Ā  :obs/A "13",
Ā  :obs/value 3.0,
Ā  :obs/color "green"}
Ā {:type :x, :local/id 3, :obs/A "15", :obs/value 7.0, :obs/color "red"}
Ā {:type :y,
Ā  :local/id 2,
Ā  :obs/A "11",
Ā  :obs/value 7.0,
Ā  :obs/shape "square"}
Ā {:type :y,
Ā  :local/id 2,
Ā  :obs/A "13",
Ā  :obs/value 4.0,
Ā  :obs/shape "circle"}
Ā {:type :y,
Ā  :local/id 6,
Ā  :obs/A "15",
Ā  :obs/value 3.0,
Ā  :obs/shape "triangle"}]

labelled-result
#{["13" 3.0 4.0] ["11" 2.0 7.0] ["15" 7.0 3.0]}

Cool stuff.
Alanā€‹


Nikita Prokopov

unread,
Sep 27, 2016, 9:04:44ā€ÆAM9/27/16
to Clojure
Alan, šŸ‘
Reply all
Reply to author
Forward
0 new messages