Created
November 21, 2016 16:53
-
-
Save zhouqiang-cl/561ea17628850ecc6539b8fdbe3efca8 to your computer and use it in GitHub Desktop.
common lisp 的通用函数定义 DEFGENERIC 和 DEFNETHOD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
语法 | |
defgeneric function-name gf-lambda-list [[option | {method-description}*]] | |
defmethod function-name {method-qualifier}* specialized-lambda-list [[declaration* | documentation]] form* | |
参数 | |
option::= (:argument-precedence-order parameter-name+) | | |
(declare gf-declaration+) | | |
(:documentation gf-documentation) | | |
(:method-combination method-combination method-combination-argument*) | | |
(:generic-function-class generic-function-class) | | |
(:method-class method-class) | |
method-description::= (:method method-qualifier* specialized-lambda-list [[declaration* | documentation]] form*) | |
参数和值的解释 | |
function-name --- 函数名 | |
generic-function-class --- 非空的 class 名 | |
gf-declaration --- 一个变量声明 | |
gf-documentation --- 字符串, 不会被求值 | |
gf-lambda-list --- 一个 Generic Function Lambda Lists | |
method-class --- 非空的 class 名 | |
描述 | |
一个通用函数 (generic function) 是由一个或多个方法组成的一个函数, 方法可用 defmethod 来定义. 当一个通用函数被调用时, | |
Lisp 会使用参数的类别与参数的特化匹配且优先级最高的方法。 | |
defgeneric 声明一个通用函数,但不提供实现. 一般来说,先用 defgeneric 声明该函数及其参数, 然后通过 defmethod 来实现该函数的方法 | |
defmethod 会隐式的创造一个generic function (如果没有使用defgeneric 提前定义的话, 会出现 | |
"Implicitly creating new generic function COMMON-LISP-USER::COMBINE." 这个警告) | |
代码 | |
* (defmethod combine (x y) | |
(list x y)) | |
STYLE-WARNING: | |
Implicitly creating new generic function COMMON-LISP-USER::COMBINE. | |
#<STANDARD-METHOD COMBINE (T T) {1004AC8B93}> | |
* (defclass stuff () ((name :accessor name :initarg :name))) | |
(defclass ice-cream (stuff) ()) | |
(defclass topping (stuff) ()) | |
#<STANDARD-CLASS STUFF> | |
#<STANDARD-CLASS ICE-CREAM> | |
#<STANDARD-CLASS TOPPING> | |
* (defmethod combine ((ic ice-cream) (top topping)) | |
(format nil "~A ice-cream with ~A topping." | |
(name ic) | |
(name top))) | |
#<STANDARD-METHOD COMBINE (ICE-CREAM TOPPING) {1004BC5173}> | |
* (combine (make-instance 'ice-cream :name 'fig) | |
(make-instance 'topping :name 'treacle)) | |
"FIG ice-cream with TREACLE topping." | |
* (combine 23 'skiddoo) | |
(23 SKIDDOO) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment