domingo, 4 de agosto de 2013

Clojure learnings

Well this post as the title says it’s going to be about clojure. Clojure is a functional programming language and it is a dialect of lisp. In this language every expression goes into parenthesis. And its syntax is kind of different because here for example to do add number you have to write ( + 2 3), or if you want to know the length of a vector you have to do (count vector) instead of vector.length as you do it in ruby.  I’m starting with this programming language, it is completely new for me, and it is very interesting.
Now I’m going to show you some simple examples to get started with Clojure.
Well let’s start with hello world:
If you do it directly from console you can write: print “Hello World”
But if we do it making a function, we can write:

(defn hello [] "Hello World")

and then just call it from console like this: (hello)
Also from what I’ve been doing I can tell that if you have to define a global variable, you have to make it an atom. So for example in the next example I did a function that counts the number of elements of a vector, but first I defined the vector.

(def example_array (atom (vector 1 2 3 4 5)))
(defn largo []
  (count  @example_array))

Other of the examples that I did was to insert an element into a vector, so in the next function I call the function with the number that I want to add to the vector.

(def example_array (atom (vector 1 2 3 4 5)))
(defn insert [arr number]
  (conj arr number))

Another thing, was trying to do the factorial function I made a try, but when I was testing it, I found that if I give number greater than 29 it says integer overflow, I’m still figuring out, but it is a good start I think.

;; for numbers < 30
(defn factorial [number]
  (if (<= number 1)
    1 (* numeber (factorial (- number 1)))))

And also, I have to tell you that comments in Clojure start with “;;”
The next function prints the numbers from 10 to 1.

(def a (atom 10))
(while (pos? @a) (do (println @a) (swap! a dec)))

Also I made a function which you give it a vector and its length, and it prints a vector with the odd numbers.

(defn oddnumber [x nums]
    (take x
      (for [n nums
            :when (odd? n)]
        n)))

Moreover, if you have a vector you can ask if it contain a determined element.

(def example_array (atom (vector 1 2 3 4 5)))
(contains? example_array 2)

And here are some more examples:

(defn square [number]

    (* number number))

(defn add [number number2]

    (+ number number2))

(defn whenexpression [number]
  (when (= 1 number) true)
)


No hay comentarios:

Publicar un comentario