Lisp - :primary Method Combination



:primary is one of the simplest method combination in CLOS. It executes the most specific applicable primary method and returns the result. Common LISP is using primary as default in generic function method combination and it is not required to be used explicityly.

When primary is used, then :before, :after and :around methods are not considered.

Defining primary function

A :before function is defined using following syntax

; define a generic function
(defgeneric combine (x y))

; define a primary implementation method for numbers
(defmethod combine ((x number) (y number))
   (+ x y))
  • (defgeneric combine (x y)) − a generic combine function is define with primary as default method combination.

  • (defmethod combine ((x number) (y number)) − combine function is defined on a generic function combine. It will be called when combine function is called with two numbers.

Example - primary Function

Following is the complete example of a primary function.

main.lisp

; define a generic combine function
(defgeneric combine (x y))

; in case of number, returns the sum of numbers
(defmethod combine ((x number) (y number))
  (+ x y))

; in case of string, returns the concatenated strings
(defmethod combine ((x string) (y string))
  (concatenate 'string x y))

; in case of lists, returned the combined list
(defmethod combine ((x list) (y list))
  (append x y))

(format t "combine 10 20: ~a~%" (combine 10 20))
(format t "combine \"Hello\" \" World!\": ~a~%" (combine "Hello" " World!"))
(format t "combine '(1 2) '(3 4): ~a~%" (combine '(1 2) '(3 4)))

Output

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

combine 10 20: 30
combine "Hello" " World!": Hello World!
combine '(1 2) '(3 4): (1 2 3 4)

Explanation

When a generic function is called , the related primary function is called as per the type of arguments passed and result is returned.

  • When combine 10 20) is called, then integer specific combine method is executed and sum of numbers 30 is returned.

  • combine 10 20: 30 is printed.

  • When combine "Hello" " World!" is called, then string specific combine method is executed and a concatenated string Hello World! is returned.

  • combine "Hello" " World!": Hello World! is printed.

  • When combine '(1 2) '(3 4) is called, then list specific combine method is executed and a combined list (1 2 3 4) is returned.

  • combine '(1 2) '(3 4): (1 2 3 4) is printed.

Advertisements