Java vs. Clojure

Couldn’t resist sharing this little Java vs. Clojure episode. Consider following interview question (stolen from a blog post):

given a string such as “AABAB”, return the string with all consecutive duplicate letters removed, ergo: “ABAB”

I’m a professional Java guy with a few years of experience, this should be a piece of cake, right? Following code is what I vomited onto my IDE in about 5 minutes. It’s not optimal, nor very beautiful, but it works. Consider it a brain dump, I’d polish it up in real project.

public class RemoveDuplicatesTest {

    @Test
    public void test() {
	assertEquals("", removeDuplicates(""));
	assertEquals("A", removeDuplicates("A"));
	assertEquals("AB", removeDuplicates("ABBBBBBBB"));
	assertEquals("ABAB", removeDuplicates("AAAABBAAB"));
    }
	
    private String removeDuplicates(String string) {
	if (string == null) {
    	    throw new IllegalArgumentException();
	}
		
	if (string.length() == 0) {
	    return "";
	}
		
	final char[] chars = string.toCharArray();
	
	char current = chars[0];
	 	
	final List acc = new ArrayList();
	 	
	for (char c : chars) {
	    if (c != current) {
	        acc.add(current);
	 			
	 	current = c;
            }
 	}
	 	
	if (acc.isEmpty() || acc.get(acc.size() - 1) != current) {
	    acc.add(current);
	}
	 	
	final StringBuilder result = new StringBuilder();
	 	
	for (Character c : acc) {
	    result.append(c);
	}
	 	
	return result.toString();
    }

}

Now, I’ve been reading up on Clojure since last week, so I gave it go as well. About half an hour of messing around in the La Clojure REPL, not too bad for a Clojure newbie. Lost some time looking up how to turn a vector into a String.

(defn removeDuplicates [arg]
  (loop [chars arg, acc []]
    (if (empty? chars) acc
      (recur (rest chars) (if (= (first chars) (last acc)) acc (conj acc (first chars)))))))

(defn to-string [s]
  (apply str s))

(= "AB" (to-string (removeDuplicates "AAABBB")))

I’m not entirely sure this qualifies as idiomatic Clojure but it looks pretty tight, would you agree? Also note that the assignment kind of pushed me to think in terms of removing duplicates from a String. The Clojure version is more generic out of the box and removes duplicates from a seq instead, but works for a String as well because a String is also a seq of characters.

I think it’s rather scary that my supposedly well-developed Java brain produces that ugly pile of code, and my embryonical Clojure brain spits out a solution that just beats the crap out the Java implementation. I’m a strong believer in the Sapir-Whorf hypothesis in the context of programming languages, this example adds yet more proof to it.

The principle of linguistic relativity holds that the structure of a language affects the ways in which its speakers are able to conceptualize their world[..]

Clojure is awesome.

Advertisements

4 thoughts on “Java vs. Clojure

  1. Sorry, it doesnt beat the crap out of your java code. Almost any programmer in any language can understand that code. The clojure is only intelligible to lispers. Get a grip.

    Also Im sure you have no idea what Clojure is doing under the hood there. Your Java code is in plain site you know exactly what its doing in terms of state manipulation.

  2. Bob, I’ve heard that exact same thing said about every pair of (new_better_language, old_popular_language) pair for the past 50 years, all the way back to various assembly languages. That you’re still using it speaks to how young you must be, and how little you know of history. That particular argument stopped being believable a couple decades ago.

    If you don’t believe me, I know a couple dinosaurs who will talk your ear off about how any decent programmer should be able to read 40 pages of 68k assembly, and the Java code is only readable to Java-ers.

  3. Not bad for a first try. I’m pretty new to Clojure, too, but loop/if/recur seems like a definite code smell, especially in Clojure. (Why do explicit looping when you can have the language do it for you?) How about:

    (apply str (map first (partition-by identity “AABAB”)))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s