Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to convert a namespaced clojure keyword to string?

Tags:

clojure

When the name function is used it correctly returns the name of a keyword as a String, as in:

(name :k) ; => "k"

A problem exists when using name on a namespaced keyword such as:

(name :n/k) ; => "k"

I can use the namespace function to correctly obtain the string I'm looking for:

(str (namespace :n/k) "/" (name :n/k)) ; => "n/k"

But for some reason I feel there should be a better way to obtain the fully qualified string.

What would be the best way to do it?

like image 756
guilespi Avatar asked May 16 '13 18:05

guilespi


Video Answer


3 Answers

Keywords actually store a symbol with the same namespace and name in a public final field and generate their string representations by prepending a colon to the string representation of that symbol. So, we can simply ask the symbol for the same and not prepend the colon:

(str (.-sym :foo/bar))
;= "foo/bar"
like image 63
Michał Marczyk Avatar answered Oct 19 '22 11:10

Michał Marczyk


(subs (str :foo/k) 1)
;=> "foo/k"
like image 37
A. Webb Avatar answered Oct 19 '22 09:10

A. Webb


Your approach is the best way to do it; it's only hard because converting a namespaced keyword to a string is an uncommon goal, and not something you'd expect to do regularly. You could write it without repeating the keyword, if you wanted:

(string/join "/" ((juxt namespace name) k))
like image 42
amalloy Avatar answered Oct 19 '22 10:10

amalloy