简体   繁体   English

如何使用leiningen引用其他文件中的函数?

[英]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. 我仍然是Clojure的新手所以我很抱歉这是一个全新的问题,但我无法在网上找到足够的答案。

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. 在这种情况下,greeter.clj在项目中与包含我的main函数的文件位于同一目录中。

For illustration purposes, I've created a project that has a directory tree like this: 为了便于说明,我创建了一个具有如下目录树的项目:

在此输入图像描述

My code for core.clj is as follows: 我的core.clj代码如下:

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

(defn -main[] (greet))

My code for greeter.clj is: 我的greeter.clj代码是:

(ns greeter)

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

Whenever I type lein run -m omg.core I get the exception mentioned above. 每当我键入lein run -m omg.core我都会得到上面提到的异常。 What am I doing wrong? 我究竟做错了什么?

the greeter namespace it at the wrong level 它在错误的级别的greeter命名空间

(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. 命名空间中的名称对应于路径中的文件夹,因此要使用/src/omg/greeter.clj中的文件,该文件应包含omg.greeter命名空间。 if you want to have it just called greeter then move it down one folder 如果你想让它只是调用greeter然后将其移动到一个文件夹

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) . 当使用require你需要拼出你正在调用的函数的命名空间,在这种情况下是(omg.greeter/greet) since this is a pain, the use function requires a namespace and adds all it's functions to the current namespace. 因为这很痛苦,所以use函数需要一个命名空间,并将其所有函数添加到当前命名空间。 Another option that is more selective is to use require with a :refer option in the namespace definition 另一个更具选择性的选项是在命名空间定义中使用require和:refer选项

(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. 大多数人将命名空间要求放在文件顶部的ns调用中。

a quick read of http://clojure.org/namespaces will hopefully help 快速阅读http://clojure.org/namespaces将有望提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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