Lisp - and Method Combination



Method combination is a powerful technique in CLOS, Common LISP Object System. This technique allows us to combine methods when multiple methods are associated with a generic method. In this chapter, we're exploring how to use and to perform and operation on multiple types of arguments.

Defining check function with method combination and

An and function is defined using following syntax

; define a generic function add
(defgeneric check (x y)
   (:method-combination and))

; check two numbers as greater than 0
(defmethod check and ((x number) (y number))
   (and (> x 0) (> y 0)))
  • defgeneric check (x y) is used to define a generic function.

  • (:method-combination and) signifies that and method combination is to be used.

  • (defmethod check and ((x number) (y number)) − check method is specialized to check two numbers are greater than zero.

  • and is essential for method combination. This method perform "and" on two number checks and returns the same.

  • Similarly, we're adding check() methods to add following parameters −

    • check number, string (length)

    • check string (length), number

    • check string (length), string (length)

Example - Use of and Function

Following is the complete example of an and function.

main.lisp

; define a generic function add
(defgeneric check (x y)
   (:method-combination and))

; check two numbers as greater than 0
(defmethod check and ((x number) (y number))
   (and (> x 0) (> y 0)))

; check number and length of string to be positive
(defmethod check and ((x number) (y string))
    (and (> x 0) (> (length y) 0)))

; check length of string and number to be positive
(defmethod check and ((x string) (y number))
    (and (> (length x) 0) (> y 0) ))

; check length of string to be positive
(defmethod check and ((x string) (y string))
    (and (> (length x) 0) (> (length y) 0) ))

; and on 10 and 5 results T
(print (check 10 5))
(terpri)
; and on 10 and test results T
(print (check 10 "test"))
(terpri)
; and on test and 20 results T
(print (check "test" 20))
(terpri)
; and on test and code results T
(print (check "test" "code"))

Output

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

T 
T 
T 
T

Explanation

Generic check function is called with different argument types. CLOS selects appropriate implementation methods based on argument types and combines the result using and method combination. and method combination treats result of each applicable method as boolean and perform and opearation on them.

  • If two positive numbers are passed, result is true.

  • In case of string, length of string is compared to be greater than zero.

  • and method combines the result of comparison and returns either T or nil as applicable.

Advertisements