在两个参数上专门化通用函数(多方法)

Dhr*_*hra 2 lisp common-lisp clos

我试图在常见的lisp中构建二叉搜索树.我使用CLOS定义了二进制搜索类,如下所示:

(defclass bst ()
  ((root :type node
         :accessor tree-root
         :initform nil
         :initarg root)))
Run Code Online (Sandbox Code Playgroud)

我试图定义一个泛型函数,它接受树对象和一个键,如果树包含键则返回布尔值true,如果树不包含键,则返回nil.

现在我有一个泛型函数的以下定义:

(defgeneric contains ((tree bst) (key))
   (:documentation "returns boolean of whether the given tree contains a particular key)
Run Code Online (Sandbox Code Playgroud)

当我将文件加载到REPL(我正在使用SBCL)时,我收到以下错误:

Required argument is not a symbol: (TREE BST)
Run Code Online (Sandbox Code Playgroud)

我误解了泛型函数的工作原理吗?我似乎无法正确定义功能.

Vat*_*ine 9

是的,defgeneric定义了一个通用函数.您可以在调用中defgeneric或通过使用指定方法defmethod.

你需要一个:

(defgeneric contains (tree key)
   (:documentation "returns boolean of whether the given tree contains a particular key")
   (:method ((tree bst) key) ...))
Run Code Online (Sandbox Code Playgroud)

要么:

(defgeneric contains (tree key)
   (:documentation "returns boolean if a given tree contains a given key"))

(defmethod contains ((tree bst) key)
  ...)
Run Code Online (Sandbox Code Playgroud)