Here can be found an interesting effort to implement the 99 Prolog problems in Clojure.

It is not clear to me that the exercise is conducted in the same way as the original one [Update: the author actually says this in the preamble]. Let me explain:

The original Prolog problems are solved without the help of the (existing) Prolog libraries, just using the basic language mechanisms. They are a good at illustrating the underlying declarative power of Prolog.

For instance, problem 1, finding the last element of a list is solved with this in Prolog:

% P01 (*): Find the last element of a list
 
% my_last(X,L) :- X is the last element of the list L
%    (element,list) (?,?)
 
% Note: last(?Elem, ?List) is predefined
 
my_last(X,[X]).
my_last(X,[_|L]) :- my_last(X,L).

Notice the in-code comment that “last is predefined”. In fact, using the Prolog library this could be done with a one liner:

?- last([1,2,3],E).
E = 3.

The offered solution in Clojure is also a one liner:

user=> (last [1 1 2 3 5 8])
8

Given a sufficiently large and clever library (and Clojure has a very nice library) all problems on the list could be solved with a one-liner.

In my opinion, an apples-to-apples comparison with the original solutions would not use the core library.
It would probably be like this for the same problem:

(defn mylast [l]
  (let [mynext (next l)]
    (if (nil? mynext)
      (first l)
      (mylast mynext)
    )
  )
)

Yep, next is in the core library also, but being a call to clojure.lang.RT, I think it is fair game to use it.

Ok, better yet, with recur, as it is on core (this is essentially a copy of the core version):

(defn mylast [s]
  (if (next s)
    (recur (next s))
    (first s)
  )
)

The Prolog exercise exposes the declarativeness and expressive power of Prolog. The Clojure example exposes mostly the cleverness of the core library.

Both are interesting points of view (I am not criticizing the Clojure solution), but they cannot be used for comparison purposes.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • LinkedIn
  • connotea
  • FriendFeed
  • Twitter

One Comment

  1. Mac says:

    Thanks for the comment. I didn’t really intend for it to be a comparison per se. I have a different goal than the original Prolog 99. I’m doing it to learn the Clojure language/libraries better. It’s also my feeling that a lot of people trying out Clojure, are trying to use it to solve some quick problems that come up in day to day. So I’d rather they learn how to do things quickly by using both the language and the library.

    In fact I think Clojure’s clever libraries and data structures is one of its greatest strength, and I’d like to expose people to that.