Learning Clojure and Emacs

Why these two, together?

Clojure, a dialect of Lisp, is best suited to be a programmed in the legendary Emacs editor, which also happens to be programmed in Lisp. Coincidence? I think not!
So, here I’m basically going to log my journey as I start learning the Clojure programming language in the Emacs editor. So this blog is going to witness Souvik Haldar learning two things at once :D

Basics steps for beginning a CLojure project


i) Install Leiningen.
ii) Setup emacs with cider and other required packages, follow this
(run M-x load-file RET <path-to-init.el> if emacs doesn’t look right)


i) Create the project using lein new app project_euler (Since we are going to solve euler’s problems for learning)
ii) Open emacs
iii) C-x C-f (then locate the core.clj file inside project_euler directory)
iv) Fire up the REPL by M-x cider-jack-in
v) Save the file by C-x C-s then compile it by C-c C-k.
vi) Switch to the REPL buffer by C-o. (or, you can see all running buffers by C-x b then RET the buffer in which REPL is running) vii) Now you can run the desired function by running it the REPL buffer by (<function-name> <arg>)

Example program written in Clojure

Question: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

(defn fibonacci [sum first second]
  (if (>= sum 4000000)
      (if (even? second)
        (recur (+ sum second) second (+ first second))
        (recur sum second (+ first second))))))

I’m currently solving Project Euler to learn to practice while learning. The solved problems can be found here. Happy Coding!