Clojure – Date and Time ”; Previous Next Since the Clojure framework is derived from Java classes, one can use the date-time classes available in Java in Clojure. The class date represents a specific instant in time, with millisecond precision. Following are the methods available for the date-time class. java.util.Date This is used to create the date object in Clojure. Syntax Following is the syntax. java.util.Date. Parameters − None. Return Value − Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. Example An example on how this is used is shown in the following program. Live Demo (ns example) (defn Example [] (def date (.toString (java.util.Date.))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. Tue Mar 01 06:11:17 UTC 2016 java.text.SimpleDateFormat This is used to format the date output. Syntax Following is the syntax. (java.text.SimpleDateFormat. format dt) Parameters − ‘format’ is the format to be used when formatting the date. ‘dt’ is the date which needs to be formatted. Return Value − A formatted date output. Example An example on how this is used is shown in the following program. Live Demo (ns example) (defn Example [] (def date (.format (java.text.SimpleDateFormat. “MM/dd/yyyy”) (new java.util.Date))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 03/01/2016 getTime Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. Syntax Following is the syntax. (.getTime) Parameters − None. Return Value − The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. Example An example on how this is used is shown in the following program. Live Demo (ns example) (import java.util.Date) (defn Example [] (def date (.getTime (java.util.Date.))) (println date)) (Example) Output The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run. 1456812778160 Print Page Previous Next Advertisements ”;
Category: clojure
Clojure – Discussion
Discuss Clojure ”; Previous Next Clojure is a high level, dynamic functional programming language. It is designed, based on the LISP programming language, and has compilers that makes it possible to be run on both Java and .Net runtime environment. This tutorial is fairly comprehensive and covers various functions involved in Clojure. All the functions are explained using examples for easy understanding. Print Page Previous Next Advertisements ”;
Clojure – Watchers
Clojure – Watchers ”; Previous Next Watchers are functions added to variable types such as atoms and reference variables which get invoked when a value of the variable type changes. For example, if the calling program changes the value of an atom variable, and if a watcher function is attached to the atom variable, the function will be invoked as soon as the value of the atom is changed. The following functions are available in Clojure for Watchers. add-watch Adds a watch function to an agent/atom/var/ref reference. The watch ‘fn’ must be a ‘fn’ of 4 args: a key, the reference, its old-state, its new-state. Whenever the reference”s state might have been changed, any registered watches will have their functions called. Syntax Following is the syntax. (add-watch variable :watcher (fn [key variable-type old-state new-state])) Parameters − ‘variable’ is the name of the atom or reference variable. ‘variable-type’ is the type of variable, either atom or reference variable. ‘old-state & new-state’ are parameters that will automatically hold the old and new value of the variable. ‘key’ must be unique per reference, and can be used to remove the watch with remove-watch. Return Value − None. Example An example on how this is used is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def x (atom 0)) (add-watch x :watcher (fn [key atom old-state new-state] (println “The value of the atom has been changed”) (println “old-state” old-state) (println “new-state” new-state))) (reset! x 2)) (Example) Output The above program produces the following output. The value of the atom has been changed old-state 0 new-state 2 remove-watch Removes a watch which has been attached to a reference variable. Syntax Following is the syntax. (remove-watch variable watchname) Parameters − ‘variable’ is the name of the atom or reference variable. ‘watchname’ is the name given to the watch when the watch function is defined. Return Value − None. Example An example on how this is used is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def x (atom 0)) (add-watch x :watcher (fn [key atom old-state new-state] (println “The value of the atom has been changed”) (println “old-state” old-state) (println “new-state” new-state))) (reset! x 2) (remove-watch x :watcher) (reset! x 4)) (Example) Output The above program produces the following output. The value of the atom has been changed old-state 0 new-state 2 You can clearly see from the above program that the second reset command does not trigger the watcher since it was removed from the watcher’s list. Print Page Previous Next Advertisements ”;
Clojure – Java Interface
Clojure – Java Interface ”; Previous Next As we already know, Clojure code runs on the Java virtual environment at the end. Thus it only makes sense that Clojure is able to utilize all of the functionalities from Java. In this chapter, let’s discuss the correlation between Clojure and Java. Calling Java Methods Java methods can be called by using the dot notation. An example is strings. Since all strings in Clojure are anyway Java strings, you can call normal Java methods on strings. An example on how this is done is shown in the following program. Example Live Demo (ns Project (:gen-class)) (defn Example [] (println (.toUpperCase “Hello World”))) (Example) The above program produces the following output. You can see from the code that if you just call the dot notation for any string method, it will also work in Clojure. Output HELLO WORLD Calling Java Methods with Parameters You can also call Java methods with parameters. An example on how this is done is shown in the following program. Example Live Demo (ns Project (:gen-class)) (defn Example [] (println (.indexOf “Hello World”,”e”))) (Example) The above program produces the following output. You can see from the above code, that we are passing the parameter “e” to the indexOf method. The above program produces the following output. Output 1 Creating Java Objects Objects can be created in Clojure by using the ‘new’ keyword similar to what is done in Java. An example on how this is done is shown in the following program. Example Live Demo (ns Project (:gen-class)) (defn Example [] (def str1 (new String “Hello”)) (println str1)) (Example) The above program produces the following output. You can see from the above code, that we can use the ‘new’ keyword to create a new object from the existing String class from Java. We can pass the value while creating the object, just like we do in Java. The above program produces the following output. Output Hello Following is another example which shows how we can create an object of the Integer class and use them in the normal Clojure commands. Example Live Demo (ns Project (:gen-class)) (defn Example [] (def my-int(new Integer 1)) (println (+ 2 my-int))) (Example) The above program produces the following output. Output 3 Import Command We can also use the import command to include Java libraries in the namespace so that the classes and methods can be accessed easily. The following example shows how we can use the import command. In the example we are using the import command to import the classes from the java.util.stack library. We can then use the push and pop method of the stack class as they are. Example Live Demo (ns Project (:gen-class)) (import java.util.Stack) (defn Example [] (let [stack (Stack.)] (.push stack “First Element”) (.push stack “Second Element”) (println (first stack)))) (Example) The above program produces the following output. Output First Element Running Code Using the Java Command Clojure code can be run using the Java command. Following is the syntax of how this can be done. java -jar clojure-1.2.0.jar -i main.clj You have to mention the Clojure jar file, so that all Clojure-based classes will be loaded in the JVM. The ‘main.clj’ file is the Clojure code file which needs to be executed. Java Built-in Functions Clojure can use many of the built-in functions of Java. Some of them are − Math PI function − Clojure can use the Math method to the value of PI. Following is an example code. Example Live Demo (ns Project (:gen-class)) (defn Example [] (println (. Math PI))) (Example) The above code produces the following output. Output 3.141592653589793 System Properties − Clojure can also query the system properties. Following is an example code. Example Live Demo (ns Project (:gen-class)) (defn Example [] (println (.. System getProperties (get “java.version”)))) (Example) Depending on the version of Java on the system, the corresponding value will be displayed. Following is an example output. Output 1.8.0_45 Print Page Previous Next Advertisements ”;
Clojure – Sequences
Clojure – Sequences ”; Previous Next Sequences are created with the help of the ‘seq’ command. Following is a simple example of a sequence creation. Live Demo (ns clojure.examples.example (:gen-class)) ;; This program displays Hello World (defn Example [] (println (seq [1 2 3]))) (Example) The above program produces the following output. (1 2 3) Following are the various methods available for sequences. Sr.No. Methods & Description 1 cons Returns a new sequence where ‘x’ is the first element and ‘seq’ is the rest. 2 conj Returns a new sequence where ‘x’ is the element that is added to the end of the sequence. 3 concat This is used to concat two sequences together. 4 distinct Used to only ensure that distinct elements are added to the sequence. 5 reverse Reverses the elements in the sequence. 6 first Returns the first element of the sequence. 7 last Returns the last element of the sequence. 8 rest Returns the entire sequence except for the first element. 9 sort Returns a sorted sequence of elements. 10 drop Drops elements from a sequence based on the number of elements, which needs to be removed. 11 take-last Takes the last list of elements from the sequence. 12 take Takes the first list of elements from the sequence. 13 split-at Splits the sequence of items into two parts. A location is specified at which the split should happen. Print Page Previous Next Advertisements ”;
Clojure – File I/O
Clojure – File I/O ”; Previous Next Clojure provides a number of helper methods when working with I/O. It offers easier classes to provide the following functionalities for files. Reading files Writing to files Seeing whether a file is a file or directory Let’s explore some of the file operations Clojure has to offer. Reading the Contents of a File as an Entire String If you want to get the entire contents of the file as a string, you can use the clojure.core.slurp method. The slurp command opens a reader on a file and reads all its contents, returning a string. Following is an example of how this can be done. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (def string1 (slurp “Example.txt”)) (println string1)) (Example) If the file contains the following lines, they will be printed as − line : Example1 line : Example2 Reading the Contents of a File One Line at a Time If you want to get the entire contents of the file as a string one line at a time, you can use the clojure.java.io/reader method. The clojure.java.io/reader class creates a reader buffer, which is used to read each line of the file. Following is an example that shows how this can be done. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (with-open [rdr (clojure.java.io/reader “Example.txt”)] (reduce conj [] (line-seq rdr)))) (Example) If the file contains the following lines, they will be printed as − line : Example1 line : Example2 The output will be shown as − [“line : Example1” “line : Example2”] Writing ‘to’ Files If you want to write ‘to’ files, you can use the clojure.core.spit command to spew entire strings into files. The spit command is the opposite of the slurp method. This method opens a file as a writer, writes content, then closes file. Following is an example. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (spit “Example.txt” “This is a string”)) In the above example, if you see the contents of the Example.txt file , you will see the contents of “This is a string”. Writing ‘to’ Files One Line at a Time If you want to write ‘to’ files one line at a time, you can use the clojure.java.io.writer class. The clojure.java.io.writer class is used to create a writer stream wherein bytes of data are fed into the stream and subsequently into the file. Following is an example that shows how the spit command can be used. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (with-open [w (clojure.java.io/writer “Example.txt” :append true)] (.write w (str “hello” “world”)))) (Example) When the above code is executed, the line “hello world” will be present in the Example.txt file. The append:true option is to append data to the file. If this option is not specified, then the file will be overwritten whenever data is written to the file. Checking to See If a File Exists To check if a file exists, the clojure.java.io.file class can be used to check for the existence of a file. Following is an example that shows how this can be accomplished. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (println (.exists (clojure.java.io/file “Example.txt”)))) (Example) If the file Example.txt exists, the output will be true. Reading from the Console To read data from the console, the read-line statement can be used. Following is an example that shows how this can be used. If you enter the (read-line) command in the REPL window, you will have the chance to enter some input in the console window. user->(read-line) Hello World The above code will produce the following output. “Hello World” Print Page Previous Next Advertisements ”;
Clojure – Reference Values
Clojure – Reference Values ”; Previous Next Reference values are another way Clojure can work with the demand to have mutable variables. Clojure provides mutable data types such as atoms, agents, and reference types. Following are the operations available for reference values. Sr.No. Operations & Description 1 ref This is used to create a reference value. When creating a reference value, there is an option to provide a validator function, which will validate the value created. 2 ref-set This function is used to set the value of a reference to a new value irrespective of whatever is the older value. 3 alter This function is used to alter the value of a reference type but in a safe manner. This is run in a thread, which cannot be accessed by another process. 4 dosync Runs the expression (in an implicit do) in a transaction that encompasses expression and any nested calls. 5 commute Commute is also used to change the value of a reference type just like alter and ref-set. Print Page Previous Next Advertisements ”;
Clojure – Maps
Clojure – Maps ”; Previous Next A Map is a collection that maps keys to values. Two different map types are provided – hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator. A map can be created in two ways, the first is via the hash-map method. Creation – HashMaps HashMaps have a typical key value relationship and is created by using hash-map function. Live Demo (ns clojure.examples.example (:gen-class)) (defn example [] (def demokeys (hash-map “z” “1” “b” “2” “a” “3”)) (println demokeys)) (example) Output The above code produces the following output. {z 1, b 2, a 3} Creation – SortedMaps SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function. Live Demo (ns clojure.examples.example (:gen-class)) (defn example [] (def demokeys (sorted-map “z” “1” “b” “2” “a” “3”)) (println demokeys)) (example) The above code produces the following output. {a 3, b 2, z 1} From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps. Sr.No. Maps & Description 1 get Returns the value mapped to key, not-found or nil if key is not present. 2 contains? See whether the map contains a required key. 3 find Returns the map entry for the key. 4 keys Returns the list of keys in the map. 5 vals Returns the list of values in the map. 6 dissoc Dissociates a key value entry from the map. 7 merge Merges two maps entries into one single map entry. 8 merge-with Returns a map that consists of the rest of the maps conj-ed onto the first. 9 select-keys Returns a map containing only those entries in map whose key is in keys. 10 rename-keys Renames keys in the current HashMap to the newly defined ones. 11 map-invert Inverts the maps so that the values become the keys and vice versa. Print Page Previous Next Advertisements ”;
Clojure – Atoms
Clojure – Atoms ”; Previous Next Atoms are a data type in Clojure that provide a way to manage shared, synchronous, independent state. An atom is just like any reference type in any other programming language. The primary use of an atom is to hold Clojure’s immutable datastructures. The value held by an atom is changed with the swap! method. Internally, swap! reads the current value, applies the function to it, and attempts to compare-and-set it in. Since another thread may have changed the value in the intervening time, it may have to retry, and does so in a spin loop. The net effect is that the value will always be the result of the application of the supplied function to a current value, atomically. Example Atoms are created with the help of the atom method. An example on the same is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn example [] (def myatom (atom 1)) (println @myatom)) (example) Output The above program produces the following result. 1 The value of atom is accessed by using the @ symbol. Clojure has a few operations that can be performed on atoms. Following are the operations. Sr.No. Operations & Description 1 reset! Sets the value of atom to a new value without regard for the current value. 2 compare-and-set! Atomically sets the value of atom to the new value if and only if the current value of the atom is identical to the old value held by the atom. Returns true if set happens, else it returns false. 3 swap! Atomically swaps the value of the atom with a new one based on a particular function. Print Page Previous Next Advertisements ”;
Clojure – Numbers
Clojure – Numbers ”; Previous Next Numbers datatype in Clojure is derived from Java classes. Clojure supports integer and floating point numbers. An integer is a value that does not include a fraction. A floating-point number is a decimal value that includes a decimal fraction. Following is an example of numbers in Clojure. (def x 5) (def y 5.25) Where ‘x’ is of the type Integer and ‘y’ is the float. In Java, the following classes are attached to the numbers defined in Clojure. To actually see that the numbers in Clojure are derived from Java classes, use the following program to see the type of numbers assigned when using the ‘def’ command. Example Live Demo (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (def x 5) (def y 5.25) (println (type x)) (println (type y))) (Example) The ‘type’ command is used to output the class associated with the value assigned to a variable. Output The above code will produce the following output. Java.lang.long Java.lang.double Number Tests The following test functions are available for numbers. Sr.No. Numbers & Description 1 zero? Returns true if the number is zero, else false. 2 pos? Returns true if number is greater than zero, else false. 3 neg? Returns true if number is less than zero, else false. 4 even? Returns true if the number is even, and throws an exception if the number is not an integer. 5 odd? Returns true if the number is odd, and throws an exception if the number is not an integer. 6 number? Returns true if the number is really a Number. 7 integer? Returns true if the number is an integer. 8 float? Returns true if the number is a float. Print Page Previous Next Advertisements ”;