Recursive Search & Prolog Batteries & Counters

After a lengthy google search, I couldn’t find a clear answer to this question: In Prolog, recursion alone makes it easy. My main problem is understanding where to place batteries and meters. Here is an example:

nXlist(N,X,[X|T]):-
    N \=0,
    N1 is N-1,
    nXList(N1,X,T).
nXList(0,_,[]).

media([X|L], N, Soma):-
   media(L, N1, Soma1),
   N is N1 + 1,
   Soma is Soma1 + X.
media([], 0, 0).

In the first example, I used the counter before recursion, but in the second example, I use AFTER. The reason I did this is because I tried to see the reason why I really can’t understand why sometimes it happens before and sometimes after ...

+4
source share
3 answers

update: , , . , , - . , user false - , . , , .


, . . , .:)

"" (, +),

a+(b+(c+....)) == (a+b)+(c+...)

() , . , .

+2

: . , (is)/2. .

, , :

:- use_module(library(clpfd)).

nXList(0,_,[]).
nXList(N,X,[X|T]):-
    N #> 0,
    N1 #= N-1,
    nXList(N1,X,T).

media([], 0, 0).
media([X|L], N, Soma):-
   N #> 0,
   N #= N1 + 1,
   Soma #= Soma1 + X,
   media(L, N1, Soma1).

, :

?- nXList(3, X, T).
T = [X, X, X] ;
false.

?- media(Xs, 3, S).
Xs = [_A, _B, _C],
_D+_A#=S,
_C+_B#=_D ;
false.

... nXList/3 :

..., length(T, N), maplist(=(X), T), ...
+2

, :

Prolog

, . , . .

So, I think the practical answer is quite simple: if a "predicate" (for example, / 2) needs a variable, you ground the variable before calling it.

For me, this helps to consider the Prolog program (a set of sentences) as grammar products and sentence arguments as attributes, either inherited (values ​​calculated before the "instruction pointer") or synthesized (values ​​calculated here "here" to return).

+2
source

Source: https://habr.com/ru/post/1669521/


All Articles