本文介绍了如何在 Prolog 中实现 arg 谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在练习中遇到了一些问题,要求我在 Prolog 中实现经典的 arg 谓词.

I have some trouble with an exercise that ask me to implement the classic arg predicate in Prolog.

arg(?Arg, +Term, ?Value)

其中 Arg 是 Term 参数列表中参数的索引.Value 是这个参数的值.

Where Arg it is the index of the argument in the arguments list of a Term. Value it is the value of this argument.

例如:

arg(1, t(f(X),Y,a), Value)
Value = f(X).

因为 f(x) 它是 t 主函子的参数列表中的第一个参数.

Because f(x) it is the first argument in the arguments list of the t main functor.

所以我试图以这种方式使用 univ =.. 谓词来解决这个练习:

So I am tryng to resolve the exercise using the univ =.. predicates in this way:

myArg(ArgIndex, Term, ArgValue) :- integer(ArgIndex),
                                   Term =.. [_|ArgsList],
                       countArg(ArgsList, ArgIndex, ArgValue).

我的想法是:ArgIndex 必须是一个整数,我可以将我的 Term 分解成它的主函子和参数列表 ArgsList 现在我必须计算参数(在这个列表中)直到ArgIndex 为 0

My idea is that: ArgIndex have to be an integer and I can decompose my Term into its main functor and the aguments list ArgsList and now I have to count the argument (in this list) untill ArgIndex is 0

但我无法计算和取这个值...

but I can't count and take this value...

推荐答案

你需要的可能是 nth(见 此处 了解语义).要实现它,以防您出于某种原因不想使用内置:

what you need is probably nth (see here for the semantics). To implement it, in case you don't want to use the built-in for some reason:

nth(1, [H|_], H).
nth(N, [_|Tail], Nth) :- N > 1, N1 is N-1, nth(N1, Tail, Nth).

(第一个参数必须是实例化的整数)

(first argument must be an instantiated integer)

如果你真的不知道如何自己实现这个谓词,你可能想看看序言的艺术",斯特林和夏皮罗.它们展示了许多 SWI-Prolog 内置程序的大量示例和参考实现.

If you really don't know how to implement this predicate yourself you might want to take a look at "The Art of Prolog", Sterling and Shapiro. They show a lot of examples and reference implementations of many of the SWI-Prolog built-ins.

这篇关于如何在 Prolog 中实现 arg 谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:25
查看更多