I tried to run two factorial functions with the same algorithm, one in Scala, the other in Clojure:
// Scala:
def factorial(n:Int) = (1 to n).foldLeft(1: BigInt)(_*_)
--
;; Clojure:
(defn factorial [x]
(reduce * (range 1N (inc x))))
The first time I enter the function to the REPL, the Clojure one evaluates (function definition, not calculating factorial) without any noticeable delay; while the scala one just paused for a short time. (Although very, very short, still noticeable.)
When I apply the function to calculate the factorial, both return the result very fast.
I would like to gain a basic understanding on the REPL. Are there any difference between the two REPL? Is Scala REPL a real REPL?
A REPL has a rather specific meaning. A "True REPL" would be one that fits the following pattern: Read Eval Print Loop. One can build a REPL in clojure in just a few lines:
(loop []
(let [string (read-line)
data (read-string line)
result (eval data)]
(println result)
(recur)))
Here you see the main parts of a true repl. read-line
reads some text from the console. read-string
converts that string to data (lists, vectors, numbers, etc.). eval
evaluates the data returning a result, and println
prints the result.
Some would argue (and I would agree) that only those systems that follow these four steps qualify to be called a repl. And some would also point out that Scala is not homoiconic, and so cannot truly have a repl.
By homoiconic, I mean that the compiler operates on the same data structures produced by the language's reader and as manipluated by the language's core constructs. For example, this is perfectly valid Clojure code:
(eval (list (symbol "+") 41 1))) ; evals to 42
So that's the gist of the debate over "real" REPLs. Only homoiconic languages like lisp (and perhaps prolog?) can have true REPLs. All others should really be named "interactive interpreters".
As far as speed goes. It's probably due to compiler complexity. The Clojure compiler is just around 10k lines of pretty linear code. Single pass, nothing special. The Scala compiler is pretty advanced, supporting things like static typing and multiple passes. Those extra features aren't needed in a language like Clojure, and they do tend to slow a compiler down a bit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With