PROLOG 中的函数输入和输出
我正在 PROLOG 中构建一些相对简单的函数,这些函数采用一个输入和一个输出。为了简单起见,类似
func(List, Item, [Item | List]).
现在,我有代码可以连续调用其中几个函数并传递结果。问题是我必须继续为所有输出创建新的变量名称。
someOtherFunc(List, Item) :-
func(List, Item, Output1),
doSomething(Output1).
这里的问题是,我实际上有几个 func
和几个 doSomething
并且非常感谢不必显式绑定 Output1
变量。有什么办法可以实现这一点吗?
I'm building some relatively simple functions in PROLOG that take one input and one output. For simplicity, something like
func(List, Item, [Item | List]).
Now, I've got code that will call several of these functions in a row and pass the result on. The issue is that I have to keep creating new variable names for all of the outputs.
someOtherFunc(List, Item) :-
func(List, Item, Output1),
doSomething(Output1).
The issue here is that I actually have several func
and several doSomething
and would really appreciate not having to bind an Output1
variable explicitly. Is there any way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您在问什么,但首先请注意,这些不是函数,而是谓词。这是一种完全不同的编程范例。变量不是放入和取出一些数据的“盒子”:它们更接近变量的数学含义,因为一旦将它们绑定到对其值的某些约束,它就永远存在。
回到你的问题,答案是否定的,你无法避免像这样绑定一些 Output1 。有时您可以添加下划线来告诉序言您不关心该值,但这样做您将失去使用该特定值的能力。在您的示例中,您想做这样的事情(以命令式伪代码):
据我所知,prolog 中没有其他方法,您只需像您那样使用中间变量即可。我可以建议的唯一改进是非常仔细地选择谓词和变量名称。
I'm not sure about what you're asking, but first of all please note that those are not functions, but predicates. This is a totally different programming paradigm. Variables are not "boxes" where you put in and out some data: they're closer to the mathematical meaning of variable, since once you bind them to some constraints on their values it's forever.
To go back to your question, the answer is no, you can't avoid binding some Output1 like that. Sometimes you can put in an underscore to tell prolog you just don't care about that value, but doing so you lose the ability to make use of that particular value. In your example you would like to do something like this (in a imperative pseudocode):
There's no other way in prolog as far as I know, you just have to use intermediate variables as you did. The only improvement I can suggest, is to choose very carefully predicates and variables names.