简体   繁体   中英

How to run clojure program from terminal

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)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM