Posts Tagged Clojure

Clojure, in Closing

After reading the book, “Programming Clojure” by Stuart Halloway, I think that I have run out of parenthesis. All kidding aside, Clojure seems like a very powerful and flexible language, if you can get a hand around it. The basic concepts are fairly straight-forward; however, as I got deeper into it I found it difficult to keep track of my location in the code and quickly lost sight of what was going on. I attribute this to a few things, one being the drastic syntactical difference between Clojure and other languages I have worked with (Java, Groovy, Ruby, Perl, etc), another is the functional programming aspect. The functional programming was tough to work around for me, having been “born” an object oriented imperative developer. I kept wanting to stuff things in variables. I would recommend Clojure to someone with more of a function programming or Lisp programming background, for whom it would be a great transition into the JVM.

I will keep an eye on it, and maybe come back to it later; however, I don’t see it becoming one of my go-to languages, as it requires too much of a paradigm shift for me to be able to produce any code with it. If I needed to use it on a regular basis, I am sure that I would catch on and probably even come to enjoy it (there are a lot of great features in Clojure), but for now it will just be an educational diversion.

If you are a curly-brace developer and looking for a real change of scenery, give Clojure a try.

Popularity: 2% [?]

  • Share/Bookmark

Tags: ,

Finding Duplicate Ints: Clojure

Finding Duplicate Ints: Clojure

I return to my common interview question (see Interview Question: Find 2 Matching Ints) with a solution based on Clojure.

I worked on the solution to this problem in a few steps, which I will share. First, I assumed that the list of numbers has been sorted:

1
2
3
4
5
6
7
8
(defn find-dupint [intseq]
    (loop [result nil its intseq]
        (if (= result (peek its))
            result
            (recur (peek its) (pop its))
        )
    )
)

This function simmply iterates over the list of numbers and returns the first number whose value matches the next number in the sequence. This code will fail if the numers are not in order and the problem definition says that they can be in any order, so I worked up the following code to sort the numbers before looping through them:

1
2
3
4
5
6
7
8
9
10
(defn find-dupint [intseq]
    (let [sorint (sort intseq)]
        (loop [result nil its sorint]
            (if (= result (first its))
                result
                (recur (first its) (rest its))
            )
        )
    )
)

Notice that I changed (peek coll) and (pop coll) to (first coll) and (rest coll), which work on sequences rather than stacks. I kept getting a ClassCastException the other way.

Now all that’s left is to have an exception thrown when no duplicated number is found. The function as written returns a nil, which is ok for Clojure I guess but not really the same behavior as the other versions of this code as it is defined, so I dipped into the Java interoperability features to add some exception throwing for the finished product:

1
2
3
4
5
6
7
8
9
10
11
12
13
(defn find-dupint [intseq]
    (let [sorint (sort intseq)]
        (loop [result nil its sorint]
            (if (= result (first its))
                (if (nil? result)
                    (throw (new IllegalArgumentException "No duplicate found!"))
                    result
                )
                (recur (first its) (rest its))
            )
        )
  )
)

Note: the IllegalArgumentException does not need to be fully qualified because the java.lang package is imported by default, just as it is in Java.

The output from using this function is shown below:

1:1 user=> (find-dupint [1 2 3])
java.lang.IllegalArgumentException: No duplicate found! (repl-1:1)

1:2 user=> (find-dupint [1 2 3 2])
2

An intesting side-effect of this version is that you are not constrained to use ints, or even numbers for that matter. You could actually use any Comparable object. (It would not be that difficult to add the ability to really generalize the function by passing in a comparator)

A few other comparable objects are tested below:

1:1 user=> (find-dupint ["a" "c" "b" "a"])
"a"

1:2 user=> (find-dupint [1.1 1.4 1.3 1.22 1.1])
1.1

I guess I should rename the function “find-dup” to reflect the broader scope than just integers.

At this point, reviewing the code, it’s not all that less verbose than the Java version, but it gets the job done. I will have to come back to this problem again as I get more experience with Clojure… I am willing to bet there is a more concise way to achieve the same results.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , , ,

Squeezing in Clojure

I had originally decided to make Scala my Language of the year for 2009, but other things came to the forefront that kept me on other tasks, both personal and development-related so I have decided to try and squeeze in Clojure before the year ends. A little light reading over lunch.

Clojure is pretty interesting so far. I found this example very interesting (from Programming Clojure by Stuart Halloway)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
    }
}

The isBlank() method checks to see whether a string is blank: either empty or consisting of only whitespace. Here is a similar implementation in Clojure:

1
(defn blank? [s] (every? #(Character/isWhitespace %) s))

if you know me, you know I like nice tight code… so this makes me happy.

I also decided that since I have spent some time on the Android platform this year, which is very standard, though limited, Java, I figured it would be a nice bit of mental exercise to learn something so completely different. Clojure is a LISP style functional language, which as can be seen from the example above, is a bit of a stretch from Java. The nice thing to note is that Clojure is a JVM-language so it runs on the standard JVM and has access to any/all Java APIs.

I have noticed that I tend to favor JVM-based languages more than others… I guess I like to learn something new without straying too far from the power and flexability that I already have avaiable. I like to keep things practical so that if/when the need arises to use one of the alternate languages that I know, I will be functional with it.

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Switch to our mobile site