简体   繁体   中英

How to implement arg predicate in Prolog?

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

arg(?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.

For example:

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

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

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).

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...

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM