clojure Ogre adding vertices - clojure

I'm using Clojure/Ogre to add vertices in Tinkergraph. Since I'm very new to this technologies, I guess that I might have missed something.
Here's what I tried:
(def graph (open-graph {(graph/GRAPH) (.getName org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph)}))
(def g (traversal graph))
(traverse g (add-V :person) (property :name "Dave"))
After these step, when I typed 'graph', I see no vertex added - output is like this:
#object[org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph 0x710f92c7 "tinkergraph[vertices:0 edges:0]"]
I guess very simple step is missed or something, but cannot figure it out.
Thanks a lot for your time. Looking forward for the solution
Thanks so much Stephen! I have one more question, if you don't mind.
Following your comment, I added codes as these:
(def dave (traverse g (add-V :person) (property :name "Dave") (iterate!)))
(def josh (traverse g (add-V :person) (property :name "Josh") (iterate!)))
After this, now I want to add an edge between dave and josh.
I tried:
(traverse g V (add-E :friends) (from dave) (to ted) (iterate!))
which returns with error.
Anything I am missing here again?
Thanks in advance!

it doesn't matter what programming language you use, you always need to iterate your traversal. In other words, you need a traversal termination step like iterate(), `toList(), etc. See the Ogre documentation for a listing of these in the "The Traversal" Section, but basically you just need to do something like this:
(traverse g (add-V :person) (property :name "Dave") (iterate!))
Note that iterate! does not return the result of a traversal. It simply consumes it. If you need the result of the traversal then you would want to look at other terminator steps. In the particular case you have you would like to have the Vertex object so, you would likely use next!

Related

How to return hiccup as a list/vector

I am passing a vector of hiccup to a funtion that just wraps it in more hiccup, but it does not return it as I would expect.
Here's an example of what I mean:
(defn wrap-fn
[input]
[div.content-box
[input]])
(defn main-fn
[vector-of-hiccup]
(foreach [hiccup from vector-of-hiccup]
(wrap-fn hiccup-from-list)))
How do I implement the made up foreach loop above?
I've tried to use 'apply' to apply the wrap-fn to each of the vector params but it only returns the first element wrapped. I've tried to creating all sorts of loops and I have similar levels of success.
I'm sure there is a way to do this, please help me find one that works.
You need something like this:
(defn wrap-fn
[input]
[:div.content-box
[input]]) ; <= you may not want to wrap `input` in a vector.
(defn main-fn
[vector-of-hiccup]
(vec
(for [item vector-of-hiccup]
(wrap-fn item))))
Note the : in :div. Hiccup vectors always start with a keyword. Also, since for returns a lazy sequence, you should convert it into a vector with vec.
Also, depending on your situation, you may want to have input instead of [input] under the :div.content-box.
See the Documentation section of the clj-template project for valuable learning information.

iterating through map and getting stack overflow error clojure

for an assignment I need to create a map from a text file in clojure, which I am new to. I'm specifically using a hash-map...but it's possible I should be using another type of map. I'm hoping someone here can answer that for me. I did try changing my hash-map to sorted-map but it gave me the same problem.
The first character in every line in the file is the key and the whole line is the value. The key is a number from 0-9999. There are 10,000 lines and each number after the first number in a line is a random number between 0 and 9999.
I've created the hashmap successfully I think. At least, its not giving me an error when I just run that code. However when I try to iterate through it, printing every value for keys 0-9999 it gives me a stack overflow error right at the middle of line 2764(in the text file). I'm hoping someone can tell me why it's doing this and a better way to do it?
Here's my code:
(ns clojure-project-441.core
(:gen-class))
(defn -main
[& args]
(def pages(def hash-map (file)))
(iter 0)
)
(-main)
(defn file []
(with-open [rdr (clojure.java.io/reader "pages.txt")]
(reduce conj [] (line-seq rdr))))
(defn iter [n]
(doseq [keyval (pages n)] (print keyval))
(if (< n 10000)
(iter (inc n))
)
)
here's a screenshot of my output
If it's relevant at all I'm using repl.it as my IDE.
Here are some screenshots of the text file, for clarity.
beginning of text file
where the error is being thrown
Thanks.
I think the specific problem that causes the exception to be thrown is caused because iter calls itself recursively too many times before hitting the 10,000 line limit.
There some issues in your code that are very common to all people learning Clojure; I'll try to explain:
def is used to define top-level names. They correspond with the concept of constants in the global scope on other programming languages. Think of using def in the same way you would use defn to define functions. In your code, you probably want to use let to give names to intermediate results, like:
(let [uno 1
dos 2]
(+ uno dos)) ;; returns 3
You are using the name hash-map to bind it to some result, but that will get in the way if you want to use the function hash-map that is used to create maps. Try renaming it to my-map or similar.
To call a function recursively without blowing the stack you'll need to use recur for reasons that are a bit long to explain. See the factorial example here: https://clojuredocs.org/clojure.core/recur
My advice would be to think of this assignment as a pipeline composed of the following small functions:
A function that reads the lines from the file (you already have this)
A function that, given a line, returns a pair: the first element of the pair is the first number of the line, the second element is the whole line (the input parameter) OR
A function that reads the first number of the line
To build the map, you have a few options; two off the top of my mind:
Use a loop construct and, for each line, "update" the hash-map to include a new key-value pair (the key is the first number, the value is the whole line), then return the whole hash-map you've built
Use a reduce operation: you create a collection of key-value pairs, then tell reduce to merge, one step at a time, into the original hash-map. The result is the hash-map you want
I think the key is to get familiar with the functions that you can use and build small functions that you can test in isolation and try to group them conveniently to solve your problem. Try to get familiar with functions like hash-map, assoc, let, loop and recur. There's a great documentation site at https://clojuredocs.org/ that also includes examples that will help you understand each function.

Associate result of operation to the hashmap value

I have 2 maps:
(def look {"directions" :look
"look" :look
"examine room" :look
})
(def quit {"exit game" :quit
"quit game" :quit
"exit" :quit
"quit" :quit
})
which are merged into one map by:
(defn actions [] (merge look quit))
and then I try to associate its result (which is a hash-map) into value of another map:
(assoc {} :1 actions)
but instead of expected result which should be:
{1: {"directions" :look, "look" :look ...
I receive
{:1 #object[fun_pro.core$actions 0x20a8027b "fun_pro.core$actions#20a8027b"]}
which is, as I understand reference to the action object.
What should I do to receive expected result? I tried also use of unquote-splicing but I'm not advanced enough to use macros yet and couldn't make it works.
EDIT1:
OK, It seem I found the solution. Instead of using (defn actions...) I should use (def actions...).
EDIT2:
To clarify why I use such a structure.
As I said in comment below, I will use this maps to compare it with the answer provided by user to find which command to use. For example if user type "show me directions", it will trigger function to display directions based on keyword "directions". The same result will be if user will ask "I look around the room" or "I examine room to find road", based on keywords "look" and "examine room".
It will be done by first splitting user input into set of strings and find if there is common word with keys from my map (turned into set). So input "show me directions" will be processed into set #{"show" "me" "directions"}. Then I will use clojure.set/intersection to find if there is common element with set of map keywords and trigger function accordingly to result (I have already coded algorithm for that).
Of course I'm open for any suggestions if there is better solution for it.
OK, It seem I found the solution on my own. Instead of using (defn actions...) I should use (def actions...).
This results of desired output.

Using the reconciler to test query in Om Next

Im sure I have read somwhere how it is possible to use the reconciler to test query expressions in Om Next directly but im not able to find the source again or figure out if this is possible based on the Om documentation. Is this possible to do so and if it is, how?
What I have right now to test is using the parser but I was hoping for a better way using the reconciler:
(parser {:state (atom state)} (om/get-query MyQuery))
This is how I currently find the value of top level keywords:
(defn query [kw]
(let [res (my-parser {:state my-reconciler} `[[~kw _]])]
(when (not-empty res) (apply val res))))
So in your case you could try:
(my-parser {:state my-reconciler} (om/get-query MyQuery))
It looks like the value for :state can either be a state you give it as in your example, or the reconciler itself as in my example.
It depends on what you mean by "test query expressions in Om Next directly"? The code you wrote above is the only way to check how the parser will interpret the query you give it.
If you're wanting to see how the app state will be normalized and denormalized using the queries you provide, maybe the documentation for idents and om/tree->db is closer to what you're looking for.

Splice a collection inside another

For work, I want to describe the format of a standard medical formular (used to report drugs side-effects) the most concise way. (Roughly, to render it afterwards through hiccup but not only, that's why I don't write it directly as a hiccup structure)
For instance, part of the description would be:
{"reportertitle" [:one-of "Dr" "Pr" "Mrs" "Mr"] ; the reporter is usually the physician
"reportergivenname" :text
"reporterfamilyname" :text
"reporterorganization" :text
"reporterdepartment" :text
....
"literaturereference" :text
"studyname" :text
....}
The keys are standard names, I cannot change them, but I'd like to be able to easily factorize things: for instance the prefix "reporter" is highly used throughout the map, I would like to be able to factorize it, for instance by doing:
{ (prefix "reporter"
"title" [:one-of "Dr" "Pr" "Mrs" "Mr"]
"givenname" :text
"familyname" :text
"organization" :text
"department" :text)
.....
"literaturereference" :text
"studyname" :text
....}
But this cannot work, because I think I cannot "integrate" (splice, I believe is the correct term) the result of 'prefix', be it a function or a macro, inside the outer map.
Is there a solution to achieve this while maintaining a high level of declarativity/conciseness? (the whole form is huge and might be read by non-developers)
(As I'm new to Clojure, pretty much every design suggestion is welcome ;) )
Thanks!
You are right in that a macro cannot tell eval to splice its result into the outer expression. A straightforward way around it would be to wrap the whole map definition in a macro that recognizes the prefix expressions and translates them into appropriate key-value sequences inside the resulting map definition.
You can also do it with functions only by just gluing the submaps with merge:
(defn pref-keys [p m] (apply hash-map (apply concat (for [[k v] m] [(str p k) v])))))
(merge
(pref-keys "reporter"
{"title" [...]
"givenname" :text
...})
{"literaturereference" :text
"studyname" :text})
Which might be a bit more verbose but probably also a bit more readable.
Edit: There is one more limitation: map literals are created before any macros (inside or outside ones) are evaluated. A macro whose argument is a map literal will get a map, not some form whose evaluation would eventually produce the map. Of course the keys and values in this map are unevaluated forms, but the map itself is a proper map (IPersistentMap).
In particular this means that the literal needs to contain an even number of forms, so this:
(my-smart-macro { (prefix "reporter" ...) } )
will fail before my-smart-macro has a chance to expand the prefix. On the other hand, this will succeed:
(another-macro { (/ 1 0) (/ 1 0) })
... provided the macro filters out the invalid arithmetic expressions from its input map.
This means that you probably do not want to pass a map literal to the macro.
In advance, I should say that this answer may not at all be what you are looking for. It would be a way of doing things that would totally alter your data structure, and you seem to maybe be saying that that's not something you can do. Anyways, I'm suggesting it because I think it would be a good change to your data structure.
So, here's how I propose you re-envision your data:
{:reporter {:title "Dr, Pr, Mrs, or Mr here"
:given-name "text here"
:family-name "text here"
:organization "text here"
:department "text here"
...}
:literature-reference "text here"
:study-name "text here"
...}
There are two changes I'm putting forth here: one is structural and the other is "cosmetic". The structural one is to nest another map in there for the reporter-related stuff. I personally think this makes the data clearer, and it is no less accessible. Instead of doing something like (get *data* "reportertitle") to access it, and (assoc *data* "reportertitle" *new-title*) to make a new version of it, you would instead to (get-in *data* [:reporter :title]) and (assoc-in *data* [:reporter :title]).
The cosmetic change is to turn those string-based keys into Clojure keywords. My main reasons for suggesting this are that it would be more idiomatic and that it would be potentially clearer to read your code. For a better discussion on why to use keywords see maybe here or here.
Now, I realize everything I've said pre-supposes that you actually can change how your data is structured and how the keywords are named. You said "The keys are standard names, I cannot change them", and this seems to indicate that this type of solution wouldn't work for you. However, maybe you could inter-convert between the two forms. If you are importing this data from somewhere and it already has the format that you give above, you would convert it into the nested-map-with-keywords form, and keep it that way while you did whatever you did with it. Then, when you export the data to actually be outputted or used (or whatever ultimate end it serves), you would convert it back to the form as you have it above.
I should say that I, personally, do not at all like this "inter-conversion" idea. I think it divides the notions of "code" and "data", which seems like such a shame considering it would be done only to have the code "look and feel nicer" than the data. That being said, I'm proposing it in case it sounds good to you.