当前位置: 动力学知识库 > 问答 > 编程问答 >

Unexpected behaviour of Prolog code

问题描述:

I want to ask about this code , why List L2 keep it's values when functions start to return it's value from Recursion , it's like 'Holding' it self , i think that list L2 must return to it's original value !!

my_reverse(L1,L2) :- my_rev(L1,L2,[]).

my_rev([],L2,L2) :- !.

my_rev([X|Xs],L2,Acc) :- my_rev(Xs,L2,[X|Acc]).

网友答案:

L2 doesn't keep its value. The program is supposed to be called as follows:

?- my_reverse([1,2,3,4], Z).
Z = [4, 3, 2, 1].

L2 is unified with Z in this example. It is kept unassigned until the first rule of the my_rev predicated is matched. Then the accumulator is unified with L2: in the last step the contents of the accumulator is "assigned to" L2.

分享给朋友:
您可能感兴趣的文章:
随机阅读: