Monday, 21 December 2009

Clojure - Wow!

I started working through "Programming Clojure" by Stuart Halloway today and had a wow moment very early on. Compare the following implementations of isBlank().

In Java:
public class StringUtils {
  public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
      return true;
    }
    for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
              return false;
            }
    }
    return true;
  }
}

In Clojure:
(defn blank? [s] (every? #(Character/isWhitespace %) s))

Wow!

2 comments:

  1. Should have mentioned, this is from p. 22 of Programming Clojure, the pdf version.

    ReplyDelete
  2. Clojure is the most interesting language around right now. The fact that relatively few programmers know about it makes it a secret weapon, but is gaining momentum fast and I think it will be really popular in a few years

    ReplyDelete