Lisp - Chaining Predicates



Chaining predicates is a programming mechanism where multiple predicates are combined to create a complex predicate or condition. Often, logical operators like and, or, not are used for chaining predicates where &

  • and predicate − returns true if all predicates are true.

  • or predicate − returns true if at least one of the predicates is true.

  • not predicate − returns the negation of predicates.

Example - Checking a positive even number

In order to check an object to be positive even number, we can combine following predicates.

  • (numberp x) − returns true if object, x is a number.

  • (evenp x) − returns true if object, x is an even number.

  • (> x 0) − returns object, x is greater than zero.

  • and − returns true if all of above predicates returns true.

(and (numberp x) (evenp x) (> x 0))

Following code shows usage of above chaining code.

main.lisp

(defparameter x 10)
(write(and (numberp x) (evenp x) (> x 0)))  ; T
(terpri)
(defparameter x 11)
(write(and (numberp x) (evenp x) (> x 0)))  ; NIL

Output

When you execute the code, it returns the following result −

T
NIL
NIL

Advantages of Chaining Predicates

  • Readability − Code is more readble as chaining predicates helps in making code more concise and clear.

  • Flexibility − Complex conditions can be achieved easily by chanining with logical predicates.

  • Maintainability − Code is highly maintainable as we can modify small piece of code instead of touching complete code base without affecting the functionality.

Built-on Functions for Chaining

Lisp provides various useful functions to assist in chaining predicates.

  • every − predicate is checked to be true for all elements in a sequence.

  • some − predicate is checked to be true for at least one element in a sequence.

  • notany − predicate is checked to be false for all elements in a sequence.

  • notevery − predicate is checked to be false for at least one element in a sequence.

Example - every

Following code shows usage of above chaining code.

main.lisp

(write(every #'numberp '(1 2 3 4 5)))  ; T as all elements are numbers
(terpri)
(write(every #'evenp '(2 4 6 7 8)))    ; NIL, as 7 is not even

Output

When you execute the code, it returns the following result −

T
NIL

Chaining predicates is a very useful programming technique where we can create complex conditions by combining simpler predicates with logical operators while readability, flexibility, and maintainability of the code.

Advertisements