Oct 12, 2010

clojure looping

There are many ways of creating loops in clojure. In this  I will give some of them.

The first way is,

user=>(loop [i 1]
                 (when (< i 20)
                 (println i)
                 (recur (+ 2 i))
             ))

This will create a loop like 1, 3, 5 ... . There are some other ways  which  gives the  same output.

user=>(dorun
         (for [i (range 1 20 2)]
         (println i)))

user=>(doseq [i (range 1 20 2)]
           (println i))


Mutual Recursion
In clojure mutual recursion is little bit harder than the other languages.
This is a simple coding to check a given number is an even or an odd number.

(def even)
(defn odd [n]
  (if (zero? n)
      false
      (even (dec n))))
(defn even [n]
  (if (zero? n)
      true
      (odd (dec n))))

So try this by typing,
(even 13)
It will give tho output as false.

Libraries
(ns example.otherns
  (:require example.mylib))
(defn check-size
  [x]
  (if (too-small x)
    (example.my)flib/add1 x)
    x))
We can defined our own libraries and can use in many programs without retyping it again and again. As a test library lets try this. Write this coding in a directory called example with the name of mylib.clj. In that file you can write like this.
(ns example.mylib)
(defn add1
  [x]
  (add x 1))

And in your program you can try by this coding
(ns example.otherns
  (:require example.mylib))
(defn check-size
  [x]
  (if (too-small x)
    (example.mylib)flib/add1 x)
    x))

or else you can use like this also
(ns example.mylib
  (:load "mylib/add1"
         "mylib/otherfunc"
         "mylib/morefuncs"))
This will add more lib files to the mylib library file. Those shoulb be plased in a director called mylib in exsample directory.


No comments:

Post a Comment

Your comments are always welcome ...