Gra
Gra

Reputation: 1594

Allow a trailing slash in a Clojure function name

For a DSL I'm implementing, I'd like to create a =/ function (which would be like not=).
Is it possible to tell the reader to allow me to do this?

My guess is "No. You dream.", but who knows…

user=> =/
RuntimeException Invalid token: =/  clojure.lang.Util.runtimeException (Util.java:221)

user=> (def =/ 1)
RuntimeException Invalid token: =/  clojure.lang.Util.runtimeException (Util.java:221)
1
RuntimeException Unmatched delimiter: )  clojure.lang.Util.runtimeException (Util.java:221)

user=> (defn =/ [x y] (not= x y))
RuntimeException Invalid token: =/  clojure.lang.Util.runtimeException (Util.java:221)
CompilerException java.lang.RuntimeException: Unable to resolve symbol: y in this context, compiling:(NO_SOURCE_PATH:0:0) 
CompilerException java.lang.RuntimeException: Unable to resolve symbol: y in this context, compiling:(NO_SOURCE_PATH:16:16) 
RuntimeException Unmatched delimiter: )  clojure.lang.Util.runtimeException (Util.java:221)

Upvotes: 2

Views: 417

Answers (2)

jmargolisvt
jmargolisvt

Reputation: 6088

The Clojure Reader treats slashes in a special way:

'/' has special meaning, it can be used once in the middle of a symbol to separate the namespace from the name, e.g. my-namespace/foo. '/' by itself names the division function.

So you won't be able to include the slash in the name of your function as the reader interprets it as the designation of a namespace.

the non obvious part is that when you type:

(defn =/ ...)

the symbol =/ is being expanded by the reader to its fully namespace qualified name of:

 my.org.namespace/=/

which violates the "one slash per name" rule.

Upvotes: 8

Terminus
Terminus

Reputation: 949

This is possible in common lisp, using "reader macros" functionality. However, from: https://en.wikibooks.org/wiki/Learning_Clojure/Reader_Macros

At this time, Clojure does not allow you to define your own reader macros, but this may change in the future.

Upvotes: 0

Related Questions