Lisp - + Method Combination
Method combination is a useful 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 plus, + symbol to add numbers with length of strings.
Defining add function with method combination +
An add function is defined using following syntax
; define a generic function add (defgeneric add (x y) (:method-combination +)) ; add two numbers (defmethod add + ((x number) (y number)) (+ x y))
defgeneric add (x y) is used to define a generic function.
(:method-combination +) signifies that + method combination is to be used.
(defmethod add + ((x number) (y number)) − add method is specialized to add two numbers.
+ is essential for method combination. This method adds two numbers and returns the same.
Similarly, we're adding add() methods to add following parameters −
add number, string (length)
add string (length), number
add string (length), string (length)
Example - Use of + Function
Following is the complete example of a + function.
main.lisp
; define a generic function add (defgeneric add (x y) (:method-combination +)) ; add two numbers (defmethod add + ((x number) (y number)) (+ x y)) ; add a number with string length (defmethod add + ((x number) (y string)) (+ x (length y))) ; add string length with a number (defmethod add + ((x string) (y number)) (+ (length x) y)) ; add strings length (defmethod add + ((x string) (y string)) (+ (length x) (length y))) ; add 10 with 5 to print 15 (print (add 10 5)) (terpri) ; add 10 with 4 to print 14 (print (add 10 "test")) (terpri) ; add 4 with 20 to print 24 (print (add "test" 20)) (terpri) ; add 4 with 4 to print 8 (print (add "test" "code"))
Output
When you execute the code, it returns the following result −
15 14 24 8
Explanation
Generic add function is called with different argument types. CLOS selects appropriate implementation methods based on argument types and combines the result using + method combination. + method combination treats result of each applicable method as numbers and sums them up.