Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are :refer and :as to be used simultaneously?

There's something I don't understand very well when I read Clojure code (say from various projects on GitHub): in the :require expression, are you supposed to use :as when you're only using functions that you're referring to using :refer? Also I'm not too sure if there's any difference between Clojure and ClojureScript from that standpoint, nor if there's any convention.

For example (I'm using the cats library for the examples but that's just an example) if I do this:

(ns example.core
  (:require
     [cats.core]
     [cats.monad.maybe :as maybe]))

from, say, the REPL I can do this:

REPL> (cats.core/mappend (maybe/just 1))

But it's not very convenient, so I may do this instead:

(ns example.core
  (:require
     [cats.core :as m]
     [cats.monad.maybe :as maybe]))

REPL> (m/mappend (maybe/just 1))

Now in case I use mappend (and a few others) all the time, I could do:

(ns example.core
  (:require
     [cats.core :refer [mappend]]
     [cats.monad.maybe :as maybe]))

REPL> (mappend (maybe/just 1))

So my question is: is there any use in using both :as and :refer, like in the following example?

(ns example.core
  (:require
     [cats.core :as m :refer [mappend]] ; does this make any sense?
     [cats.monad.maybe :as maybe]))

I understand that I may be using, say, mappend all the time and may want to refer to it directly as mappend but bind not that often as to using :refer but yet often enough so that writing cats.core/bind is not convenient, so I'd use m/bind?

So is there any rule? Like if you're using :as you should not use :refer, or the other way round? Or that you should always use both?

What about ClojureScript, is it working in exactly the same way?

like image 986
Cedric Martin Avatar asked Mar 10 '23 03:03

Cedric Martin


1 Answers

You're right on the use case; things that you use quite often, you may want to :refer to directly, otherwise, just use the :as alias to access it. There's no problem with doing both.

I personally tend to prefer :as unless it's very clear what namespace the :refered function came from (e.g. I would recognize >!! without a prefix, but find m/bind more readable).

The most widely used style guide afaik suggests that using them in conjunction is fine, but prefer :as to :refer in most cases: https://github.com/bbatsov/clojure-style-guide#comprehensive-ns-declaration

Clojurescript should be exactly the same for :refer and :as in ns.

like image 151
Alejandro C. Avatar answered Mar 19 '23 06:03

Alejandro C.