Munge

munge is an expose but undocumented method in clojure.core library. This is an example usage:

user=> (munge "abc")
"abc"

user=> (munge :abc)
"_COLON_abc"

user=> (munge "Lin-Ju")
"Lin_Ju"

user=> (munge :?)
"_COLON__QMARK_"

user=> (munge "?")
"_QMARK_"

user=> (munge '?')
_QMARK__SINGLEQUOTE_

user=> (defn foo [] (println "foo"))
#'user/foo
user=> foo
#<user$foo user$foo@43352742>
user=> (munge foo)
"user$foo_CIRCA_43352742"

Explanation is cheap, show me the source!

(defn munge [s]
  ((if (symbol? s)
       symbol
       str)
   (clojure.lang.Compiler/munge (str s))))
static final public IPersistentMap CHAR_MAP =
		PersistentHashMap.create('-', "_",
//		                         '.', "_DOT_",
':', "_COLON_",
'+', "_PLUS_",
'>', "_GT_",
'<', "_LT_",
'=', "_EQ_",
'~', "_TILDE_",
'!', "_BANG_",
'@', "_CIRCA_",
'#', "_SHARP_",
'\'', "_SINGLEQUOTE_",
'"', "_DOUBLEQUOTE_",
'%', "_PERCENT_",
'^', "_CARET_",
'&', "_AMPERSAND_",
'*', "_STAR_",
'|', "_BAR_",
'{', "_LBRACE_",
'}', "_RBRACE_",
'[', "_LBRACK_",
']', "_RBRACK_",
'/', "_SLASH_",
'\\', "_BSLASH_",
'?', "_QMARK_");

static public String munge(String name){
	StringBuilder sb = new StringBuilder();
	for(char c : name.toCharArray())
		{
		String sub = (String) CHAR_MAP.valAt(c);
		if(sub != null)
			sb.append(sub);
		else
			sb.append(c);
		}
	return sb.toString();
}

To sum up, it’s a nice function probably used to

  • Make java-digestible names. The munged string is then Java-safe.
  • Make a string from runtime as persist file name.