Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference functions in other files with leiningen?

I'm still fairly new to Clojure so I apologize if this is a completely newbie question but I wasn't able to find a sufficient answer online.

Basically, my problem is that any time I try to run my project, I get an error like:

Exception in thread "main" java.lang.RuntimeException: java.io.FileNotFoundException: Could not locate greeter__init.class or greeter.clj on classpath: 

In this case, greeter.clj is in the project in the same directory as the file containing my main function.

For illustration purposes, I've created a project that has a directory tree like this:

enter image description here

My code for core.clj is as follows:

(ns omg.core
(require [greeter]))

(defn -main[] (greet))

My code for greeter.clj is:

(ns greeter)

(defn greet [] println("Hello world"))

Whenever I type lein run -m omg.core I get the exception mentioned above. What am I doing wrong?

like image 492
Carl Veazey Avatar asked May 02 '12 00:05

Carl Veazey


1 Answers

the greeter namespace it at the wrong level

(ns omg.greeter)

The names in namespace correspond to the folders in the path so to use the file in /src/omg/greeter.clj that file should contain the omg.greeter namespace. if you want to have it just called greeter then move it down one folder

When using require you need to spell out the namespace of the function you are calling, in this case that would be (omg.greeter/greet). since this is a pain, the use function requires a namespace and adds all it's functions to the current namespace. Another option that is more selective is to use require with a :refer option in the namespace definition

(ns omg.core
    (require [omg.greeter :refer :all]))

or

(ns omg.core
    (require [omg.greeter :refer [greet]]))

Most people put the namespace requirements into the ns call at the top of the file.

a quick read of http://clojure.org/namespaces will hopefully help

like image 125
Arthur Ulfeldt Avatar answered Nov 19 '22 11:11

Arthur Ulfeldt