gpt4 book ai didi

lisp - 使用 defstruct 在结构中定义函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:49 25 4
gpt4 key购买 nike

是否可以像函数一样定义结构的槽之一并访问槽以使用该函数?如果是,如何使用它?例如,像这样:

(defstruct problem
state
(player (defun getplayer (some-state) (findplayer 1 some-state)))
(points (defun getpoints (some-state someplayer) (findpoints someplayer some-state)))
)

最佳答案

我会使用以下两种技术之一:

第一个是存储命名函数的符号,而不是将函数存储在槽中。请注意,这假设命名函数在结构 def 本身之外的其他地方定义。

(Defstruct problem
State
(Points 'getpoints)
(Player 'getplayer))

这可能以类似于以下的方式使用:

 (Defvar p (make-problem ...))
(Funcall (problem-points p) x)
(Funcall (problem-player p) x y)

这样做的原因是,当提供一个符号时,Funcall 在调用之前自动解析它的 fdefinition。第二种方法非常相似,但不是代表命名函数的符号,而是将插槽直接设置为匿名函数(称为“lambda 表达式”)。这种方法与您列出的示例有额外的相似之处,我是分配给槽值的函数是在结构的定义或实例化中定义的,不依赖于在其他地方定义的函数。所以:

(Defstruct problem
State
(Points (lambda (arg0) (some-computation arg0)))
(Player (lambda (arg0 arg1) (other-computation arg0 arg1))))

然后:

 (Defvar q (make-problem ...))
(Funcall (problem-points q) x)
(Funcall (problem-player q) x y)

希望对您有所帮助!

关于lisp - 使用 defstruct 在结构中定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19913289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com