COBOL – Data Types ”; Previous Next Data Division is used to define the variables used in a program. To describe data in COBOL, one must understand the following terms − Data Name Level Number Picture Clause Value Clause 01 TOTAL-STUDENTS PIC9(5) VALUE ”125”. | | | | | | | | | | | | Level Number Data Name Picture Clause Value Clause Data Name Data names must be defined in the Data Division before using them in the Procedure Division. They must have a user-defined name; reserved words cannot be used. Data names give reference to the memory locations where actual data is stored. They can be elementary or group type. Example The following example shows valid and invalid data names − Valid: WS-NAME TOTAL-STUDENTS A100 100B Invalid: MOVE (Reserved Words) COMPUTE (Reserved Words) 100 (No Alphabet) 100+B (+ is not allowed) Level Number Level number is used to specify the level of data in a record. They are used to differentiate between elementary items and group items. Elementary items can be grouped together to create group items. Sr.No. Level Number & Description 1 01 Record description entry 2 02 to 49 Group and Elementary items 3 66 Rename Clause items 4 77 Items which cannot be sub-divided 5 88 Condition name entry Elementary items cannot be divided further. Level number, Data name, Picture clause, and Value clause (optional) are used to describe an elementary item. Group items consist of one or more elementary items. Level number, Data name, and Value clause (optional) are used to describe a group item. Group level number is always 01. Example The following example shows Group and Elementary items − DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NAME PIC X(25). —> ELEMENTARY ITEM 01 WS-CLASS PIC 9(2) VALUE ”10”. —> ELEMENTARY ITEM 01 WS-ADDRESS. —> GROUP ITEM 05 WS-HOUSE-NUMBER PIC 9(3). —> ELEMENTARY ITEM 05 WS-STREET PIC X(15). —> ELEMENTARY ITEM 05 WS-CITY PIC X(15). —> ELEMENTARY ITEM 05 WS-COUNTRY PIC X(15) VALUE ”INDIA”. —> ELEMENTARY ITEM Picture Clause Picture clause is used to define the following items − Data type can be numeric, alphabetic, or alphanumeric. Numeric type consists of only digits 0 to 9. Alphabetic type consists of letters A to Z and spaces. Alphanumeric type consists of digits, letters, and special characters. Sign can be used with numeric data. It can be either + or –. Decimal point position can be used with numeric data. Assumed position is the position of decimal point and not included in the data. Length defines the number of bytes used by the data item. Symbols used in a Picture clause − Sr.No. Symbol & Description 1 9 Numeric 2 A Alphabetic 3 X Alphanumeric 4 V Implicit Decimal 5 S Sign 6 P Assumed Decimal Example The following example shows the use of PIC clause − Live Demo IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC S9(3)V9(2). 01 WS-NUM2 PIC PPP999. 01 WS-NUM3 PIC S9(3)V9(2) VALUE -123.45. 01 WS-NAME PIC A(6) VALUE ”ABCDEF”. 01 WS-ID PIC X(5) VALUE ”A121$”. PROCEDURE DIVISION. DISPLAY “WS-NUM1 : “WS-NUM1. DISPLAY “WS-NUM2 : “WS-NUM2. DISPLAY “WS-NUM3 : “WS-NUM3. DISPLAY “WS-NAME : “WS-NAME. DISPLAY “WS-ID : “WS-ID. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : +000.00 WS-NUM2 : .000000 WS-NUM3 : -123.45 WS-NAME : ABCDEF WS-ID : A121$ Value Clause Value clause is an optional clause which is used to initialize the data items. The values can be numeric literal, alphanumeric literal, or figurative constant. It can be used with both group and elementary items. Example The following example shows the use of VALUE clause − Live Demo IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC 99V9 VALUE IS 3.5. 01 WS-NAME PIC A(6) VALUE ”ABCD”. 01 WS-ID PIC 99 VALUE ZERO. PROCEDURE DIVISION. DISPLAY “WS-NUM1 : “WS-NUM1. DISPLAY “WS-NAME : “WS-NAME. DISPLAY “WS-ID : “WS-ID. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − WS-NUM1 : 03.5 WS-NAME : ABCD WS-ID : 00 Print Page Previous Next Advertisements ”;
Category: Computer Programming
COBOL – File Organization
COBOL – File Organization ”; Previous Next File organization indicates how the records are organized in a file. There are different types of organizations for files so as to increase their efficiency of accessing the records. Following are the types of file organization schemes − Sequential file organization Indexed sequential file organization Relative file organization The syntaxes in this module, mentioned along with their respective terms, only refer to their usage in the program. The complete programs using these syntaxes would be discussed in the chapter ”File handling Verbs”. Sequential File Organization A sequential file consists of records that are stored and accessed in sequential order. Following are the key attributes of sequential file organization − Records can be read in sequential order. For reading the 10th record, all the previous 9 records should be read. Records are written in sequential order. A new record cannot be inserted in between. A new record is always inserted at the end of the file. After placing a record into a sequential file, it is not possible to delete, shorten, or lengthen a record. Order of the records, once inserted, can never be changed. Updation of record is possible. A record can be overwritten, if the new record length is same as the old record length. Sequential output files are good option for printing. Syntax Following is the syntax of sequential file organization − INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT file-name ASSIGN TO dd-name-jcl ORGANIZATION IS SEQUENTIAL Indexed Sequential File Organization An indexed sequential file consists of records that can be accessed sequentially. Direct access is also possible. It consists of two parts − Data File contains records in sequential scheme. Index File contains the primary key and its address in the data file. Following are the key attributes of sequential file organization − Records can be read in sequential order just like in sequential file organization. Records can be accessed randomly if the primary key is known. Index file is used to get the address of a record and then the record is fetched from the data file. Sorted index is maintained in this file system which relates the key value to the position of the record in the file. Alternate index can also be created to fetch the records. Syntax Following is the syntax of indexed sequential file organization − INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT file-name ASSIGN TO dd-name-jcl ORGANIZATION IS INDEXED RECORD KEY IS primary-key ALTERNATE RECORD KEY IS rec-key Relative File Organization A relative file consists of records ordered by their relative address. Following are the key attributes of relative file organization − Records can be read in sequential order just like in sequential and indexed file organization. Records can be accessed using relative key. Relative key represents the record’s location relative to the address of the start of the file. Records can be inserted using relative key. Relative address is calculated using relative key. Relative file provides the fastest access to the records. The main disadvantage of this file system is that if some intermediate records are missing, they will also occupy space. Syntax Following is the syntax of relative file organization − INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT file-name ASSIGN TO dd-name-jcl ORGANIZATION IS RELATIVE RELATIVE KEY IS rec-key Print Page Previous Next Advertisements ”;
Clojure – Quick Guide
Clojure – Quick Guide ”; Previous Next Clojure – Overview Clojure is a high level, dynamic functional programming language. Clojure is designed based on the LISP programming language and has compilers which makes it run on both Java and .Net runtime environment. Before we talk about Clojure, let’s just have a quick description of LISP programming language. LISPs have a tiny language core, almost no syntax, and a powerful macro facility. With these features, you can bend LISP to meet your design, instead of the other way around. LISP has been there for a long time dating back to 1958. Common LISP reads in an expression, evaluates it, and then prints out the result. For example, if you want to compute the value of a simple mathematical expression of 4+6 then you type in. USER(1) (+ 4 6) Clojure has the following high-level key objectives as a programming language. It is based on the LISP programming language which makes its code statements smaller than traditional programming languages. It is a functional programming language. It focuses on immutability which is basically the concept that you should not make any changes to objects which are created in place. It can manage the state of an application for the programmer. It supports concurrency. It embraces existing programming languages. For example, Clojure can make use of the entire Java ecosystem for management of the running of the code via the JVM. The official website for Clojure is https://clojure.org/ Clojure – Environment There are a variety of ways to work with Clojure as a programming language. We will look at two ways to work with Clojure programming. Leiningen − Leiningen is an essential tool to create, build, and automate Clojure projects. Eclipse Plugin − There is a plugin called CounterClockwise, which is available for Eclipse for carrying out Clojure development in the Eclipse IDE. Leiningen Installation Ensure the following System requirements are met before proceeding with the installation. System Requirements JDK JDK 1.7 or above Memory 2 GB RAM (recommended) Step 1 − Download the binary installation. Go to the link http://leiningen-wininstallerto get the Windows Installer. Click on the option to start the download of the Groovy installer. Step 2 − Launch the Installer and click the Next button. Step 3 − Specify the location for the installation and click the Next button. Step 4 − The setup will detect the location of an existing Java installation. Click the Next button to proceed. Step 5 − Click the Install button to begin the installation. After the installation is complete, it will give you the option to open a Clojure REPL, which is an environment that can be used to create and test your Clojure programs. Eclipse Installation Ensure the following System requirements are met before proceeding with the installation. System Requirements JDK JDK 1.7 or above Eclipse Eclipse 4.5 (Mars) Step 1 − Open Eclipse and click the Menu item. Click Help → Eclipse Marketplace. Step 2 − Type in the keyword Clojure in the dialog box which appears and hit the ‘Go’ button. The option for counterclockwise will appear, click the Install button to begin the installation of this plugin. Step 3 − In the next dialog box, click the Confirm button to begin the installation. Step 4 − In the next dialog box, you will be requested to accept the license agreement. Accept the license agreement and click the Finish button to continue with the installation. The installation will begin, and once completed, it will prompt you to restart Eclipse. Once Eclipse is restarted, you will see the option in Eclipse to create a new Clojure project. Clojure – Basic Syntax In order to understand the basic syntax of Clojure, let’s first look at a simple Hello World program. Hello World as a Complete Program Write ‘Hello world’ in a complete Clojure program. Following is an example. Example Live Demo (ns clojure.examples.hello (:gen-class)) (defn hello-world [] (println “Hello World”)) (hello-world) The following things need to be noted about the above program. The program will be written in a file called main.clj. The extension ‘clj’ is the extension name for a clojure code file. In the above example, the name of the file is called main.clj. The ‘defn’ keyword is used to define a function. We will see functions in details in another chapter. But for now, know that we are creating a function called helloworld, which will have our main Clojure code. In our Clojure code, we are using the ‘println’ statement to print “Hello World” to the console output. We then call the hello-world function which in turn runs the ‘println’ statement. The above program produces the following output. Output Hello World General Form of a Statement The general form of any statement needs to be evaluated in braces as shown in the following example. (+ 1 2) In the above example, the entire expression is enclosed in braces. The output of the above statement is 3. The + operator acts like a function in Clojure, which is used for the addition of numerals. The values of 1 and 2 are known as parameters to the function. Let us consider another example. In this example, ‘str’ is the operator which is used to concatenate two strings. The strings “Hello” and “World” are used as parameters. (str “Hello” “World”) Example If we combine the above two statements and write a program, it will look like the following. Live Demo (ns clojure.examples.hello (:gen-class)) (defn Example [] (println (str “Hello World”)) (println (+ 1 2))) (Example) Output The above program produces the following output. Hello World 3 Namespaces A namespace is used to define a logical boundary between modules defined in Clojure. Current Namespace This defines the current namespace in which the current Clojure code resides in. Syntax *ns* Example In the REPL command window run the following command. *ns* Output When we run the above command, the output will defer depending on what is the current namespace. Following is an
Clojure – Databases
Clojure – Databases ”; Previous Next In order to use the database functionality, please ensure to first download the jdbc files from the following url − https://codeload.github.com/clojure/java.jdbc/zip/master You will find a zip file which has the necessary drivers for Clojure to have the ability to connect to databases. Once the zip file is extracted, ensure to add the unzipped location to your classpath. The main file for database connectivity is a file called jdbc.clj in the location clojure/java. The clojure jdbc connector supports a wide variety of databases, some of which are the following. H2Database Oracle Microsoft SQL Server MySQL PostgreSQL In our example, we are going to use MySQL DB as an example. The following operations are possible in Clojure with regards to Databases. Database Connection Before connecting to a MySQL database, make sure of the following − You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID “testuser” and password “test123” are set to access TESTDB. Ensure you have downloaded the ‘mysql jar file’ and added the file to your classpath. You have gone through MySQL tutorial to understand MySQL Basics. Syntax Following is the syntax to create a connection in Clojure. (def connection_name { :subprotocol “protocol_name” :subname “Location of mysql DB” :user “username” :password “password” }) Parameters − ‘connection_name’ is the name to be given to the connection. ‘subprotocol’ is the protocol to be used for the connection. By default we will be using the mysql protocol. ‘subname’ is the url to connect to the mysql db along with the database name. ‘user’ is the username used to connect to the database. ‘password’ is the password to be used to connect to the database. Return Value − This will provide a connection string, which can be used in subsequent mysql operations. The following example shows how to connect to the tables in the information schema and retrieve all the data in the table. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/information_schema” :user “root” :password “shakinstev”}) (println (sql/query mysql-db [“select table_name from tables”] :row-fn :table_name))) Querying Data Querying data on any database means to fetch some useful information from the database. Once a database connection is established, you are ready to make a query into this database. Following is the syntax by which data can be queried using Clojure. Syntax clojure.java.jdbc/query dbconn [“query”] :row-fn :sequence Parameters − ‘dbconn’ is the name of the connection used to connect to the database. ‘query’ is the query string used to fetch data from the database. ‘:sequence’ is by default all the rows of data fetched from the database and is returned as a sequence. The necessary operations on the sequence can then be done to see what data has been fetched. Return Value − This will return a sequence, which will have the rows of data from the query operation. The following example shows how to connect to the employee table and fetch the first_name column of the rows in the table. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (println (sql/query mysql-db [“select first_name from employee”] :row-fn :first_name))) From the above code, we can see that The query of “select first_name from employee” is passed as the query string. The :first_name is the sequence, which is returned as a result of the fetch operation. If we assume that there is just one row in our database which contains a first_name value of John, following will be the output of the above program. (John) Inserting Data It is required when you want to create your records into a database table. Following is the syntax by which data can be inserted using Clojure. This is done by using the ‘insert!’ function. Syntax clojure.java.jdbc/insert! :table_name {:column_namen columnvalue} Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘{:column_namen columnvalue }’ is a map of all the column names and values, which need to be added as a row in the table. Return Value − This will return nil if the insertion is made successfully. The following example shows how to insert a record into the employee table in the testdb database. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (sql/insert! mysql-db :employee {:first_name “John” :last_name “Mark” :sex “M” :age 30 :income 30})) If you now check your MySQL database and the employee table, you will see that the above row will be successfully inserted in the table. Deleting Data Rows can be deleted from a table by using the ‘delete!’ function. Following is the syntax on how this operation can be performed. Syntax clojure.java.jdbc/delete! :table_name [condition] Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘condition’ is the condition used to determine which row needs to be deleted from the table. Return Value − This will return the number of rows deleted. The following example shows how to delete a record from the employee table in the testdb database. The example deletes a row from the table based on the condition that the age is equal to 30. Example (ns test.core (:require [clojure.java.jdbc :as sql])) (defn -main [] (def mysql-db { :subprotocol “mysql” :subname “//127.0.0.1:3306/testdb” :user “root” :password “shakinstev”}) (println (sql/delete! mysql-db :employee [“age = ? ” 30]))) If you had a record which had a row with age equal to the value of 30, that row will be deleted. Updating Data Rows can be updated from a table by using the ‘update!’ function. Following is the syntax on how this operation can be performed. Syntax clojure.java.jdbc/update! :table_name {setcondition} [condition] Parameters − ‘:table_name’ is the name of the table in which the insertion needs to be made. ‘setcondition’ is the column which needs
Clojure – Libraries
Clojure – Libraries ”; Previous Next One thing which makes the Clojure library so powerful is the number of libraries available for the Clojure framework. We have already seen so many libraries used in our earlier examples for web testing, web development, developing swing-based applications, the jdbc library for connecting to MySQL databases. Following are just a couple of examples of few more libraries. data.xml This library allows Clojure to work with XML data. The library version to be used is org.clojure/data.xml “0.0.8”. The data.xml supports parsing and emitting XML. The parsing functions will read XML from a Reader or InputStream. Example Following is an example of the data processing from a string to XML. (ns clojure.examples.example (use ”clojure.data.xml) (:gen-class)) (defn Example [] (let [input-xml (java.io.StringReader. “<?xml version = “1.0” encoding = “UTF-8″?><example><clo><Tutorial>The Tutorial value</Tutorial></clo></example>”)] (parse input-xml))) #clojure.data.xml.Element{ :tag :example, :attrs {}, :content (#clojure.data.xml.Element { :tag :clo, :attrs {}, :content (#clojure.data.xml.Element { :tag :Tutorial, :attrs {},:content (“The Tutorial value”)})})} (Example) data.json This library allows Clojure to work with JSON data. The library version to be used is org.clojure/data.json “0.2.6”. Example Following is an example on the use of this library. Live Demo (ns clojure.examples.example (:require [clojure.data.json :as json]) (:gen-class)) (defn Example [] (println (json/write-str {:a 1 :b 2}))) (Example) Output The above program produces the following output. {“a”:1,”b”:2} data.csv This library allows Clojure to work with ‘csv’ data. The library version to be used is org.clojure/data.csv “0.1.3”. Example Following is an example on the use of this library. (ns clojure.examples.example (require ”[clojure.data.csv :as csv] ”[clojure.java.io :as io]) (:gen-class)) (defn Example [] (with-open [in-file (io/reader “in-file.csv”)] (doall (csv/read-csv in-file))) (with-open [out-file (io/writer “out-file.csv”)] (csv/write-csv out-file [[“:A” “a”] [“:B” “b”]]))) (Example) In the above code, the ‘csv’ function will first read a file called in-file.csv and put all the data in the variable in-file. Next, we are using the write-csv function to write all data to a file called out-file.csv. Print Page Previous Next Advertisements ”;
Clojure – Regular Expressions ”; Previous Next A regular expression is a pattern that is used to find substrings in text. Regular expressions are used in a variety of programming languages and used a lot in LISP type programming languages. Following is an example of a regular expression. //d+ The above regular expression is used to find one more occurrence of a digit in a string. The // characters are used to ensure that characters ‘d’ and ‘+’ are used to represent a regular expression. In general, regular expressions works with the following set of rules. There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($): Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. The metacharacter { and } is used to match a specific number of instances of the preceding character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret ithin the square brackets as in [∧a–z] and represents all characters other than those specified. The following methods are available for regular expressions. Sr.No. Methods & Description 1 re-pattern Returns an instance of java.util.regex.Pattern. This is then used in further methods for pattern matching. 2 refind Returns the next regex match, if any, of string to pattern, using java.util.regex.Matcher.find() 3 replace The replace function is used to replace a substring in a string with a new string value. The search for the substring is done with the use of a pattern. 4 replace-first The replace function is used to replace a substring in a string with a new string value, but only for the first occurrence of the substring. The search for the substring is done with the use of a pattern. Print Page Previous Next Advertisements ”;
Clojure – Predicates
Clojure – Predicates ”; Previous Next Predicates are functions that evaluate a condition and provide a value of either true or false. We have seen predicate functions in the examples of the chapter on numbers. We have seen functions like ‘even?’ which is used to test if a number is even or not, or ‘neg?’ which is used to test if a number is greater than zero or not. All of these functions return either a true or false value. Following is an example of predicates in Clojure. Live Demo (ns clojure.examples.example (:gen-class)) ;; This program displays Hello World (defn Example [] (def x (even? 0)) (println x) (def x (neg? 2)) (println x) (def x (odd? 3)) (println x) (def x (pos? 3)) (println x)) (Example) The above program produces the following output. true false true true In addition to the normal predicate functions, Clojure provides more functions for predicates. The following methods are available for predicates. Sr.No. Methods & Description 1 every-pred Takes a set of predicates and returns a function ‘f’ that returns true if all of its composing predicates return a logical true value against all of its arguments, else it returns false. 2 every? Returns true if the predicate is true for every value, else false. 3 some Returns the first logical true value for any predicate value of x in the collection of values. 4 not-any? Returns false if any of the predicates of the values in a collection are logically true, else true. Print Page Previous Next Advertisements ”;
Clojure – Macros
Clojure – Macros ”; Previous Next In any language, Macros are used to generate inline code. Clojure is no exception and provides simple macro facilities for developers. Macros are used to write code-generation routines, which provide the developer a powerful way to tailor the language to the needs of the developer. Following are the methods available for Macros. defmacro This function is used to define your macro. The macro will have a macro name, a parameter list and the body of the macro. Syntax Following is the syntax. (defmacro name [params*] body) Parameters − ‘name’ is the name of the macro. ‘params’ are the parameters assigned to the macro. ‘body’ is the body of the macro. 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 [] (defmacro Simple [] (println “Hello”)) (macroexpand ”(Simple))) (Example) Output The above program produces the following output. Hello From the above program you can see that the macro ‘Simple’ is expanded inline to ‘println’ “Hello”. Macros are similar to functions, with the only difference that the arguments to a form are evaluated in the case of macros. macro-expand This is used to expand a macro and place the code inline in the program. Syntax Following is the syntax. (macroexpand macroname) Parameters − ‘macroname’ is the name of the macro which needs to be expanded. Return Value − The expanded macro. Example An example on how this is used is shown in the following program. Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (defmacro Simple [] (println “Hello”)) (macroexpand ”(Simple))) (Example) Output The above program produces the following output. Hello Macro with Arguments Macros can also be used to take in arguments. The macro can take in any number of arguments. Following example showcases how arguments can be used. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (defmacro Simple [arg] (list 2 arg)) (println (macroexpand ”(Simple 2)))) (Example) The above example places an argument in the Simple macro and then uses the argument to add argument value to a list. Output The above program produces the following output. (2 2) Print Page Previous Next Advertisements ”;
Clojure – Date & Time
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 ”;
Clojure – Destructuring
Clojure – Destructuring ”; Previous Next Destructuring is a functionality within Clojure, which allows one to extract values from a data structure, such as a vector and bind them to symbols without having to explicitly traverse the datastructure. Let’s look at an example of what exactly Destructuring means and how does it happen. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b c d] my-vector] (println a b c d))) (Example) The above program produces the following output. Output 1 2 3 4 In the above example, following things are to be noted − We are defining a vector of integers as 1 ,2, 3 and 4. We are then using the ‘let’ statement to assign 4 variables (a, b, c, and d) to the my-vector variable directly. If we run the ‘println’ statement on the four variables, we can see that they have already been assigned to the values in the vector respectively. So clojure has destructured the my-vector variable which has four values when it was assigned using the ‘let’ statement. The deconstructed four values were then assigned to the four parameters accordingly. If there are excess variables which don’t have a corresponding value to which they can be assigned to, then they will be assigned the value of nil. The following example makes this point clear. Example Live Demo (ns clojure.examples.hello (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b c d e] my-vector] (println a b c d e))) (Example) The above program produces the following output. You can see from the output that since the last variable ‘e’ does not have a corresponding value in the vector, it accounts to nil. Output 1 2 3 4 nil the-rest The ‘the-rest’ variable is used to store the remaining values, which cannot get assigned to any variable. An example on how this is used is shown in the following program. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-vector [1 2 3 4]) (let [[a b & the-rest] my-vector] (println a b the-rest))) (Example) The above program produces the following output. From the output, you can clearly see that the values of 3 and 4 cannot be assigned to any variable so they are assigned to the ‘the-rest’ variable. Output 1 2 (3 4) Destructuring Maps Just like vectors, maps can also be destructured. Following is an example of how this can be accomplished. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-map {“a” 1 “b” 2}) (let [{a “a” b “b”} my-map] (println a b))) (Example) The above program produces the following output. From the program you can clearly see that the map values of “a” and “b” are assigned to the variables of a and b. Output 1 2 Similarly in the case of vectors, if there is no corresponding value in the map when the destructuring happens, then the variable will be assigned a value of nil. Following is an example. Example Live Demo (ns clojure.examples.example (:gen-class)) (defn Example [] (def my-map {“a” 1 “b” 2}) (let [{a “a” b “b” c “c”} my-map] (println a b c))) (Example) The above program produces the following output. Output 1 2 nil Print Page Previous Next Advertisements ”;