Clojure – Useful Resources ”; Previous Next The following resources contain additional information on Clojure. Please use them to get more in-depth knowledge on this topic. Python Programming Certification 2024 Most Popular 9 Courses 1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular 7 Courses 1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller 7 Courses 1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;
Category: Computer Programming
Clojure – Applications
Clojure – Applications ”; Previous Next Clojure has some contributed libraries which have the enablement for creating Desktop and Web-based applications. Let’s discuss each one of them. Sr.No. Applications & Description 1 Desktop – See-saw See-saw is a library which can be used for creating desktop applications. 2 Desktop – Changing the Value of Text The value of the content in the window can be changed by using the ‘config!’ option. In the following example the config! option is used to change the window content to the new value of “Good Bye”. 3 Desktop – Displaying a Modal Dialog Box A modal dialog box can be shown by using the alert method of the see-saw class. The method takes the text value, which needs to be shown in the modal dialog box. 4 Desktop – Displaying Buttons Buttons can be displayed with the help of the button class. 5 Desktop – Displaying Labels Labels can be displayed with the help of the label class. 6 Desktop – Displaying Text Fields Text Fields can be displayed with the help of the text class. Web Applications – Introduction To create a web application in Clojure you need to use the Ring application library, which is available at the following link https://github.com/ring-clojure/ring You need to ensure you download the necessary jars from the site and ensure to add it as a dependency for the Clojure application. The Ring framework provides the following capabilities − Sets things up such that an http request comes into your web application as a regular Clojure HashMap, and likewise makes it so that you can return a response as a HashMap. Provides a specification describing exactly what those request and response maps should look like. Brings along a web server (Jetty) and connects your web application to it. The Ring framework automatically can start a web server and ensures the Clojure application works on this server. Then one can also use the Compojure framework. This allows one to create routes which is now how most modern web applications are developed. Creating your first Clojure application − The following example shows how you can create your first web application in Clojure. (ns my-webapp.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]])) (defroutes app-routes (GET “/” [] “Hello World”) (route/not-found “Not Found”)) (def app (wrap-defaults app-routes site-defaults)) Let’s look at the following aspects of the program − The ‘defroutes’ is used to create routes so that request made to the web application to different routes can be directed to different functions in your Clojure application. In the above example, the “/” is known as the default route, so when you browse to the base of your web application, the string “Hello World” will be sent to the web browser. If the user hits any url which cannot be processed by the Clojure application, then it will display the string “Not Found”. When you run the Clojure application, by default your application will be loaded as localhost:3000, so if you browse to this location, you will receive the following output. Web Applications – Adding More Routes to Your Web Application You can also add more routes to your web application. The following example shows how to achieve this. (ns my-webapp.handler (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]])) (defroutes app-routes (GET “/” [] “Hello World”) (GET “/Tutorial” [] “This is a tutorial on Clojure”) (route/not-found “Not Found”)) (def app (wrap-defaults app-routes site-defaults)) You can see that adding a route in the application is as easy as just adding another GET function with the url route. (GET “/Tutorial” [] “This is a tutorial on Clojure”) If you browse to the location http://localhost:3000/Tutorial, you will receive the following output. Print Page Previous Next Advertisements ”;
Clojure – Overview
Clojure – Overview ”; Previous Next 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/ Print Page Previous Next Advertisements ”;
Clojure – Home
Clojure Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice. Prerequisites Before proceeding with this tutorial, familiarity with Java and LISP programming language is preferred. Print Page Previous Next Advertisements ”;
Clojure – Basic Syntax
Clojure – Basic Syntax ”; Previous Next 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 example of an output. The namespace of the Clojure code is − clojure.examples.hello (ns clojure.examples.hello (:gen-class)) (defn Example [] (println (str “Hello World”)) (println (+ 1 2))) (Example) Require Statement in Clojure Clojure code is packaged in libraries. Each Clojure library belongs to a namespace, which is analogous to a Java package. You can load a Clojure library with the ‘Require’ statement. Syntax (require quoted-namespace-symbol) Example Following is an example of the usage of this statement. (ns clojure.examples.hello (:gen-class)) (require ‘clojure.java.io’) (defn Example [] (.exists (file “Example.txt”))) (Example) In the above code, we are using the ‘require’ keyword to import the namespace clojure.java.io which has all the functions required for input/output functionality. Since we not have the required library, we can use the ‘file’ function in the above code. Comments in Clojure Comments are used to document your code. Single line comments are identified by using the ;; at any position in the line. Following is an example. Example (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (println “Hello World”)) (Example) Delimiters In Clojure, statements can be split or delimited by using either the curved or square bracket braces. Example Following are two examples. Live Demo (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (println (+ 1 2 3))) (Example) Output The above program produces the following output. 6 Example Following is another example. Live Demo (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (println [+ 1 2 3])) (Example) Output The above program produces the following output. [#object[clojure.core$_PLUS_ 0x10f163b “clojure.core$_PLUS_@10f163b”] 1 2 3] Whitespaces Whitespaces can be used in Clojure to split different components of a statement for better clarity. This can be done with the assistance of the comma (,) operator. For example, the following two statements are equivalent and the output of both the statements will be 15. (+ 1 2 3 4 5) (+ 1, 2, 3, 4, 5) Although Clojure ignores commas, it sometimes uses them to make things easier for the programmer to read. For instance, if you have a hash map like the following (def a-map {:a 1 :b 2 :c 3}) and ask for its value in the REPL window, Clojure will print the output as {:a 1, :b 2, :c 3}. The results are easier to read, especially if you’re looking at a large amount of data. Symbols In Clojure, symbols are equivalent to identifiers in other programming languages. But unlike other programming languages, the compiler sees symbols as actual string values. As a symbol is a value, a symbol can be stored in a collection, passed as an argument to a function, etc., just like any other object. A symbol can only contain alphanumeric characters and ‘* + ! / . : – _ ?’ but must not begin with a numeral or colon. Following are valid examples of symbols. tutorial-point! TUTORIAL +tutorial+ Clojure Project Structure Finally let’s talk about a typical project structure for a Clojure project. Since Clojure code runs on Java virtual machine, most of the project structure within Clojure is similar to what you would find in a java project. Following is the snapshot of a sample project structure in Eclipse for a Clojure project. Following key things need to be noted about the above program structure. demo_1 − This is the package in which the Clojure code file is placed. core.clj − This is the main Clojure code file, which will contain the code for the Clojure application. The Leiningen folder contains files like clojure-1.6.0.jar which is required to run any Clojure-based application. The
Clojure – Strings
Clojure – Strings ”; Previous Next A String literal is constructed in Clojure by enclosing the string text in quotations. Strings in Clojure need to be constructed using the double quotation marks such as “Hello World”. Example Following is an example of the usage of strings in Clojure. Live Demo (ns clojure.examples.hello (:gen-class)) (defn hello-world [] (println “Hello World”) (println “This is a demo application”)) (hello-world) Output The above program produces the following output. Hello World This is a demo application Basic String Operations Clojure has a number of operations that can be performed on strings. Following are the operations. Sr.No. String Operations & Description 1 str The concatenation of strings can be done by the simple str function. 2 format The formatting of strings can be done by the simple format function. The format function formats a string using java.lang.String.format. 3 count Returns the number of characters in the string. 4 subs Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive. 5 compare Returns a negative number, zero, or a positive number when ‘x’ is logically ”less than”, ”equal to”, or ”greater than” ‘y’. 6 lower-case Converts string to all lower-case. 7 upper-case Converts string to all upper-case. 8 join Returns a string of all elements in collection, as returned by (seq collection), separated by an optional separator. 9 split Splits string on a regular expression. 10 split-lines Split strings is based on the escape characters n or rn. 11 reverse Reverses the characters in a string. 12 replace Replaces all instance of a match in a string with the replacement string. 13 trim Removes whitespace from both ends of the string. 14 triml Removes whitespace from the left hand side of the string. 15 trimr Removes whitespace from the right hand side of the string. Print Page Previous Next Advertisements ”;
Clojure – Environment
Clojure – Environment ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Clojure – Data Types
Clojure – Data Types ”; Previous Next Clojure offers a wide variety of built-in data types. Built-in Data Types Following is a list of data types which are defined in Clojure. Integers − Following are the representation of Integers available in Clojure. Decimal Integers (Short, Long and Int) − These are used to represent whole numbers. For example, 1234. Octal Numbers − These are used to represent numbers in octal representation. For example, 012. Hexadecimal Numbers − These are used to represent numbers in representation. For example, 0xff. Radix Numbers − These are used to represent numbers in radix representation. For example, 2r1111 where the radix is an integer between 2 and 36, inclusive. Floating point The default is used to represent 32-bit floating point numbers. For example, 12.34. The other representation is the scientific notation. For example, 1.35e-12. char − This defines a single character literal. Characters are defined with the backlash symbol. For example, /e. Boolean − This represents a Boolean value, which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example, “Hello World”. Nil − This is used to represent a NULL value in Clojure. Atom − Atoms provide a way to manage shared, synchronous, independent state. They are a reference type like refs and vars. Bound Values Since all of the datatypes in Clojure are inherited from Java, the bounded values are the same as in Java programming language. The following table shows the maximum allowed values for the numerical and decimal literals. literals Ranges Short -32,768 to 32,767 int -2,147,483,648 to 2,147,483,647 long -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float 1.40129846432481707e-45 to 3.40282346638528860e+38 double 4.94065645841246544e-324d to 1.79769313486231570e+308d Class Numeric Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed. Name java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double Example The following program shows a consolidated clojure code to demonstrate the data types in Clojure. Live Demo (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] ;; The below code declares a integer variable (def x 1) ;; The below code declares a float variable (def y 1.25) ;; The below code declares a string variable (def str1 “Hello”) (println x) (println y) (println str1)) (Example) Output The above program produces the following output. 1 1.25 Hello Print Page Previous Next Advertisements ”;
Clojure – Operators
Clojure – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Clojure has the following types of operators − Arithmetic operators Relational operators Logical operators Bitwise operators Note − In Clojure, operators and operands work in the following syntax manner. Syntax (operator operand1 operand2 operandn) For example, Example (+ 1 2) The above example does an arithmetic operation on the numbers 1 and 2. Arithmetic Operators Clojure language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available in Clojure. Show Examples Operator Description Example + Addition of two operands (+ 1 2) will give 3 − Subtracts second operand from the first (- 2 1) will give 1 * Multiplication of both operands (* 2 2) will give 4 / Division of numerator by denominator (float (/ 3 2)) will give 1.5 inc Incremental operators used to increment the value of an operand by 1 inc 5 will give 6 dec Incremental operators used to decrement the value of an operand by 1 dec 5 will give 4 max Returns the largest of its arguments max 1 2 3 will return 3 min Returns the smallest of its arguments min 1 2 3 will return 1 rem Remainder of dividing the first number by the second rem 3 2 will give 1 Relational Operators Relational operators allow comparison of objects. Following are the relational operators available in Clojure. Show Examples Operator Description Example = Tests the equality between two objects (= 2 2) will give true not= Tests the difference between two objects (not = 3 2) will give true < Checks to see if the left object is less than the right operand (< 2 3) will give true <= Checks to see if the left object is less than or equal to the right operand (<= 2 3) will give true > Checks to see if the left object is greater than the right operand (> 3 2) will give true >= Checks to see if the left object is greater than or equal to the right operand (>= 3 2) will give true Logical Operators Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy. Show Examples Operator Description Example and This is the logical “and” operator (or true true) will give true or This is the logical “or” operator (and true false) will give false not This is the logical “not” operator (not false) will give true The following code snippet shows how the various operators can be used. Bitwise Operators Clojure provides four bitwise operators. Following are the bitwise operators available in Clojure. Show Examples Sr.No. Operator & Description 1 bit-and This is the bitwise “and” operator 2 bit-or This is the bitwise “or” operator 3 bit-xor This is the bitwise “xor” or Exclusive ‘or’ operator 4 bit-not This is the bitwise negation operator Following is the truth table showcasing these operators. p q p&q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Operator Precedence As is the case with LISPs in general, there is no need to worry about operator precedence. This is one of the benefits of S-Expressions and prefix notation. All functions evaluate left to right and inside out. The operators in Clojure are just functions, and everything is fully parenthesized. Print Page Previous Next Advertisements ”;
Clojure – Functions
Clojure – Functions ”; Previous Next Clojure is known as a functional programming language, hence you would expect to see a lot of emphasis on how functions work in Clojure. This chapter covers what all can be done with functions in Clojure. Sr.No. Functions & Description 1 Defining a Function A function is defined by using the ‘defn’ macro. 2 Anonymous Functions An anonymous function is a function which has no name associated with it. 3 Functions with Multiple Arguments Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type. 4 Variadic Functions Clojure offers the ‘case’ statement which is similar to the ‘switch’ statement available in the Java programming language. 5 Higher Order Functions Higher-order functions (HOFs) are functions that take other functions as arguments. HOFs are an important functional programming technique and are quite commonly used in Clojure. Print Page Previous Next Advertisements ”;