Dom*_*riš 1 types overloading function common-lisp
是否有一个 Common Lisp 构造是 to labelswhat defmethodis to defun?也就是说,我想使用labels(或类似的东西)来定义几个具有相同名称但它们接受的参数不同的局部函数,并让编译器在其中进行选择。
作为 MWE,我想实现以下功能
(defmethod write-first-item-type ((lst list))
"Writes the type of the first item in lst."
(labels ((write-single ()
(format t "a single float"))
(write-double ()
(format t "a double float")))
(format t "The first item is: ~A.~%"
(cond ((eql (type-of (car lst)) 'single-float)
(write-single))
((eql (type-of (car lst)) 'double-float)
(write-double))
(t
(format t "unknown"))))))
Run Code Online (Sandbox Code Playgroud)
像
(defmethod write-first-item-type ((lst list))
"Should write the type of the first item in lst but does not compile."
(label-method ((write-type ((item single-float))
(format t "a single float"))
(write-type ((ifem double-float))
(format t "a double float")))
(format t "The first item is: ~A.~%"
(write-type (car lst)))))
Run Code Online (Sandbox Code Playgroud)
不可否认,我的 MWE 相当愚蠢。我的实际动机是,在清理我的源代码时,我想将一堆小辅助函数(使用defmethod)放入使用它们的一个大函数中。也可以随意评论这个动机!
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |