How to run clojure program from terminal - clojure

I have just begun learning clojure and I'm using the Textmate editor for writing the scripts. However, I am not able to figure out how to run it from the terminal. Like I type the clj filename.clj command but nothing happens. Do I need to include the function name also somewhere because I have a function that takes a number as an argument.
Here is my code that I want to run from the terminal:
(defn next-collatz-num [n]
(if (even? n)
(quot n 2)
(inc (* n 3))))
(defn collatz [n]
(take-while #(< 1 %)(iterate next-collatz-num n)))
(defn max-count-collatz [n]
(when (> n 0)
(first
(reduce
#(if (> (last %1)(last %2)) %1 %2)
[1 1] (map #(list % (count (collatz %))) (range 1 (inc n)))))))
(max-count-collatz 999999)

Clojure has a much more interactive environment than just running a whole script at the terminal command prompt.
TL;DR, install leiningen, create a project.clj, then run lean repl.
If you don't want to create a project.clj, or if you're curious how to do it the hard way, read on...
You can start a Clojure read-eval-print-loop (REPL) interactive prompt with
java -cp clojure-1.6.0.jar clojure.main
(download the latest Clojure jar here).
Once you're in the REPL, load the code file:
(load-file "my-script.clj")
Now, you can call the function directly:
(max-count-collatz 5)
If it doesn't work as you'd expect, change the code, save and reload it in the REPL:
(require 'my-script :reload-all)

While it is possible to run individual Clojure files using Clojure.jar, one of the best things about Clojure is the leiningen dependency manager and build tool. Creating a project is easy, and for anything more than a single file with no external dependencies, it is a huge improvement over using java and Clojure.jar directly.

Related

MorphAnnotator.addLemma produces a NullPointerException for a particular text stream

(def ^:private props
(doto (java.util.Properties.)
(.put "annotators" "tokenize, ssplit, pos, lemma, parse")
(.put "parse.maxlen" (str (-> config :nlp :max-sentence-length)))
(.put "pos.maxlen" (str (-> config :nlp :max-sentence-length)))))
(def ^:private pipeline (StanfordCoreNLP. props))
(defn- annotated-doc [s]
(.process pipeline s))
(def input-text (slurp "/home/you/some.txt"))
(annotated-doc input-text)
Which then produces either a properly annotated result as expected or it produces this exception:
java.lang.NullPointerException: null
MorphaAnnotator.java:68 edu.stanford.nlp.pipeline.MorphaAnnotator.addLemma
MorphaAnnotator.java:55 edu.stanford.nlp.pipeline.MorphaAnnotator.annotate
AnnotationPipeline.java:67 edu.stanford.nlp.pipeline.AnnotationPipeline.annotate
StanfordCoreNLP.java:881 edu.stanford.nlp.pipeline.StanfordCoreNLP.annotate
StanfordCoreNLP.java:910 edu.stanford.nlp.pipeline.StanfordCoreNLP.process
(Unknown Source) sun.reflect.GeneratedMethodAccessor27.invoke
DelegatingMethodAccessorImpl.java:43
sun.reflect.DelegatingMethodAccessorImpl.invoke
Method.java:606 java.lang.reflect.Method.invoke
Reflector.java:93 clojure.lang.Reflector.invokeMatchingMethod
Reflector.java:28 clojure.lang.Reflector.invokeInstanceMethod
The text file is very vanilla. I have reduced my annotators list down to what produces the issue. I have 6 GB of memory configured for it. The text file is 3886 characters long, UTF-8 BOM formatted file. It works with partial text from this file just fine. It even works if I take the whole file as in (take 3886 input-text). So I'm stumped. Not sure what to make of it. Any suggestions?
Here is a link to the text file I was using: http://nectarineimp.com/spooky-action.txt
From my project.clj file:
:dependencies [[org.clojure/clojure "1.6.0"]
[edu.stanford.nlp/stanford-corenlp "3.3.1"]
[edu.stanford.nlp/stanford-corenlp "3.3.1" :classifier "models"]]
I agree that this is was a bug in the Annotator. I'm not sure what your configuration settings were for:
(def ^:private props
(doto (java.util.Properties.)
(.put "annotators" "tokenize, ssplit, pos, lemma, parse")
(.put "parse.maxlen" (str (-> config :nlp :max-sentence-length)))
(.put "pos.maxlen" (str (-> config :nlp :max-sentence-length)))))
But they were irrelevant in reproducing the issue. I recently upgraded a project to version 3.5.2 and your code block ran without issues (CoreNLP Version History).
Running in 3.1.1 produces your results exactly. It looks like at version 3.5.0 a Java 1.8 JVM is required.
This bug appears to be fixed in version 3.4 of CoreNLP as well, which doesn't require JVM updates.
Your question was posted a while ago, so I'm pretty sure you've already figured all this out, but for the sake of Google, I've left these comments.

rand-nth always yields the same result after compilation

I've project created via Leiningen with core.clj:
(ns cotd.core
(:gen-class)
(:use [clojure.repl :only (doc)]))
(defmacro eval-doc
[form]
(let [resulting-symbol (eval form)]
`(doc ~resulting-symbol)))
(defn- random-function-name []
(rand-nth (keys (ns-publics 'clojure.core))))
(defn -main
"Display random doc page"
[& args]
(eval-doc (random-function-name)))
And after compiling and running it always yields the same result:
$ java -jar cotd.jar
-------------------------
clojure.core/unchecked-negate
([x])
Returns the negation of x, a long.
Note - uses a primitive operator subject to overflow.
$ java -jar cotd.jar
-------------------------
clojure.core/unchecked-negate
([x])
Returns the negation of x, a long.
Note - uses a primitive operator subject to overflow.
But with two consecutive calls:
(do
(eval-doc (random-function-name))
(eval-doc (random-function-name))))
It yields two different results in single "call".
What I've tried is googling, reading, etc. but I have no clues what's going on...
How to invoke this rand-nth dynamically?
The problem wasn't with rand-nth but because the resulting-symbol in the let statement is produced during the compilation phase. #beyamor provided answer here: Unable to get random (doc) from a namespace

what text to speech and speech recognition libraries are available for Clojure?

what text to speech and speech recognition libraries are available for Clojure?
So far I have found
https://github.com/klutometis/speech-recognition
https://github.com/klutometis/speech-synthesis
both of these use Google and thus depend of the web.
I'm looking for ones that don't depend on the internet to work
I think this is a pretty much unexplored territory as far as existing Clojure libraries go.
Your best bet is probably to look at the many available Java speech recognition libraries and use them from Clojure - they are going to be much more mature and capable at this point.
You may want to look at:
http://cmusphinx.sourceforge.net/sphinx4/
Using Java libraries from Clojure is extremely easy - it is generally as simple as importing the right classes and doing (.someMethod someObject arg1 arg2)
If you do create a Clojure wrapper for a speech recogniser, please do contribute it back to the community! I know quite a few people (myself included) would be interested in doing some speech-related work in Clojure.
So far I have been able to use the native system's TTS here is my code,
maybe this will help someone?
(use '[speech-synthesis.say :as say])
(use '[clojure.java.shell :only [sh]])
(defn festival [x](sh "sh" "-c" (str "echo " x " | festival --tts")))
(defn espeak [x] (sh "espeak" x))
(defn mac-say[x] (sh "say" x))
(defn check-if-installed[x] (:exit(sh "sh" "-c" (str "command -v " x " >/dev/null 2>&1 || { echo >&2 \"\"; exit 1; }"))))
(defn engine-check[]
(def engines (conj["Google" ]
(if (= (check-if-installed "festival") 0) "Festival" )
(if (= (check-if-installed "espeak") 0) "ESpeak" )
(if (= (check-if-installed "say") 0) "Say" ))) ;; Say is the Apple say command
(remove nil? engines))
(defn set-engine [eng](cond (= eng "Google")(def speak say)
(= eng "Festival" )(def speak festival)
(= eng "ESpeak") (def speak espeak)
(= eng "Say") (def speak mac-say)))
then to use
(set-engine "Festival") ;; set the engine
(speak "Hello, I can talk") ;; speak your text
I have used espeak via a JNI java library I wrote to generate speech from text in clojure. The basic library is available on github. Unfortunately, for unrelated reasons, I've been forced to put my focus towards a different problem for the time being. However, drop me a message if you want to use my library to interface with espeak from clojure - I can send you some exmaples of how I used it.

user.clj and init.clj dont work?

This is my problem:
I need run some code every time I open a new repl, searching in Google I found that I can use the file init.clj or the user.clj (with Leiningen)
This is the code I need to run:
(set! *print-length* 103)
(println "hello")
(println *print-length*)
These are the results with both of the files:
[~/project]$ lein repl
hello <- this is the println, so the file is excecuted
103 <- this is the println of *print-length* apparently change
REPL started; server listening on localhost port 20875
user=> *print-length*
nil <- but the val of *print-length* don't change
Is there something I need to do or do I have some error?
Thanks to all!
(alter-var-root #'*print-length* (constantly 103)) in ~/user.clj works for me.
As far as I know set! doesn't work outside of a binding's dynamic scope.
lein's init.clj runs in the leiningen process, not in your project process. See https://github.com/technomancy/leiningen (search for init.clj)

Clojure (read-line) doesn't wait for input

I am writing a text game in Clojure. I want the player to type lines at the console, and the game to respond on a line-by-line basis.
Research showed me that (read-line) is the way one is meant to get text lines from standard input in Clojure, but it is not working for me.
I am in a fresh Leiningen project, and I have added a :main clause to the project.clj pointing to the only source file:
(ns textgame.core)
(defn -main [& args]
(println "Entering -main")
; (flush) ;makes no difference if flush are commented out
(let [input (read-line)]
(println "ECHO:" input))
; (flush)
(println "Exiting -main"))
using lein run yields:
Entering -main
ECHO: nil
Exiting -main
In other words, there is no opportunity to enter text at the console for (read-line) to read.
How should I get Clojure to wait for characters and newline to be entered and return the corresponding string?
(I am using GNOME Terminal 2.32.1 on Linux Mint 11, Leiningen 1.6.1.1 on Java 1.6.0_26 Java HotSpot(TM) 64-Bit Server VM, Clojure version 1.2.1.)
Update: If I run lein repl, I can (println (read-line)), but not when I have a -main function and run using lein run.
Try "lein trampoline run". See http://groups.google.com/group/leiningen/browse_thread/thread/a07a7f10edb77c9b for more details also from https://github.com/technomancy/leiningen:
Q: I don't have access to stdin inside my project.
A: There's a problem in the library that Leiningen uses to spawn new processes that blocks access to console input. This means that functions like read-line will not work as expected in most contexts, though the repl task necessarily includes a workaround. You can also use the trampoline task to launch your project's JVM after Leiningen's has exited rather than launching it as a subprocess.
I have had similar problems and resorted to building a jar file and then running that.
lein uberjar
java -jar project-standalone.jar
It's a bit slower, though it got me unstuck. An answer that works from the repl would
be better
Wrap your read-line calls with the macro with-read-line-support which is now in ns swank.core [since swank-clojure 1.4+ I believe]:
(use 'swank.core)
(with-read-line-support
(println "a line from Emacs:" (read-line)))
Thanks to Tavis Judd for the fix.
You can use read and use a string as input.
Not sure about the lein aspects of the problem, but definitely in emacs it is impossible to make stdin work. However, if you want to get text from the user, you can easily do it using a JOptionPane like this code from my little tic-tac-toe program:
(defn get-input []
(let [input (JOptionPane/showInputDialog "Enter your next move (row/column)")]
(map #(Integer/valueOf %) (.split input "/"))))