Clojure – Predicates

Clojure predicates

In this guide, we will discuss Clojure Predicates. 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.

(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
1every-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.
2every?
Returns true if the predicate is true for every value, else false.
3some
Returns the first logical true value for any predicate value of x in the collection of values.
4not-any?
Returns false if any of the predicates of the values in a collection are logically true, else true.

Next Topic : Click Here

This Post Has 3 Comments

Leave a Reply