Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure import versus :import

Reading the clojure API for import I see that :import in the ns macro is preferred to import, however when i'm coding using swank/slime/emacs, I can't c-x c-e the (ns .. ) s-expression to get the deps into the repl, but using (import ...) I can.

Whats the reason why :import is preferred over import, and is there fast way to import the deps from a (ns ...) s-expr from my .clj file to the repl? (Same question can be generalized to :use and :refer.. thanks)

like image 644
ChrisR Avatar asked Jul 13 '11 01:07

ChrisR


3 Answers

Here is my preferred workflow:

  • Start Swank/Slime
  • Open the file I want to work on in Emacs
  • Do C-c C-k to compile and load the file in question
  • Do , followed by i, then type the name of the namespace you're working on and press Enter

Now your Slime REPL should be in the namespace you're working on, and you can add to the ns declaration at the top and just C-c C-k as you change things (including your ns imports).

like image 132
semperos Avatar answered Oct 07 '22 01:10

semperos


I'm not sure why c-x c-e wouldn't work, but C-c C-c on the ns expression does work correctly as long as the namespace already exists.

like image 2
Joost Diepenmaat Avatar answered Oct 07 '22 01:10

Joost Diepenmaat


The (ns ... ) form is preferred since your code will read more easily. All the namespace declarations will be collected at the top of the file. You see this enforced by the compiler in languages like Java. Also, the containing macro ns removes the need for you to quote symbols. The same can be said of use, import, refer, etc.

I think that the C-x C-e slime short-cut will send the piece of code to the connected swank server, and have it evaluated. For example the form:

(ns my.test
   (:require [clojure.contrib.logging :as log])
   (:import [java.io File]))

will create a new namespace called my.test which includes contrib logging and java.io File. It will not change the namespace of the repl. To do that press C-c M-p from the file you are editing, and you will be prompted with the name of the namespace of that file to switch to (unless you are already in that namespace). Press enter to select. C-c C-z should switch to the repl. Now instead of the user=> prompt, you should see my.test=>, indicating that you are in that namespace.

The workflow I have set-up is to compile the whole file on save, using:

(defun ed/clojure-compile-on-save (&optional args)
  "Compile with slime on save"
  (interactive)
  (if (and (eq major-mode 'clojure-mode)
      (slime-connected-p))
      (slime-compile-and-load-file)))
(add-hook 'after-save-hook 'ed/clojure-compile-on-save)

That way, when ever I save the file, it gets compiled and loaded by the swank server, and I use the repl for experiments in the namespace I'm working on.

like image 2
l0st3d Avatar answered Oct 07 '22 03:10

l0st3d