PROLOG 中的函数输入和输出

发布于 2024-12-01 00:46:08 字数 403 浏览 0 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

没︽人懂的悲伤 2024-12-08 00:46:08

我不确定您在问什么,但首先请注意,这些不是函数,而是谓词。这是一种完全不同的编程范例。变量不是放入和取出一些数据的“盒子”:它们更接近变量的数学含义,因为一旦将它们绑定到对其值的某些约束,它就永远存在。

回到你的问题,答案是否定的,你无法避免像这样绑定一些 Output1 。有时您可以添加下划线来告诉序言您不关心该值,但这样做您将失去使用该特定值的能力。在您的示例中,您想做这样的事情(以命令式伪代码):

var list = ..., item = ...;
doSomething(func(list, item));

据我所知,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):

var list = ..., item = ...;
doSomething(func(list, item));

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.

雄赳赳气昂昂 2024-12-08 00:46:08
func1(Input1, Input2) :-
   func2(Input1, Input2, Output1),
   useFun(Output1, Output2).
/* Output2 the result I obtain from the function useFun */
func1(Input1, Input2) :-
   func2(Input1, Input2, Output1),
   useFun(Output1, Output2).
/* Output2 the result I obtain from the function useFun */
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文