解释这个Prolog程序的作用?

时间:2013-12-09 03:40:15

标签: prolog

我正在研究Prolog,我遇到了以下计划。当我使用查询执行此程序时,例如:mysterious([2,3,4,5,6,7,8],L),它给出了答案20.我不明白获得此结果的流程。任何人都可以帮我理解这段代码吗?

如何为上述查询产生答案20?

mysterious([],0).
mysterious([X],X).
mysterious([X,Y|Xs], Res) :-
    mysterious(Xs, Res1),
    Res is X + Res1.

2 个答案:

答案 0 :(得分:3)

因为这是一个基本的程序,我会给你一个提示。首先,这个:

foo([]).
foo([X]).
foo([X,Y|Rest]) :-
    foo(Rest).

也可以写成:

foo([]).
foo([First|Rest]) :-
    bar(Rest, First).

bar([], Last).
bar([This|Rest], Prev) :-
    foo(Rest).

这是不必要的冗长,但更明确。然而,在你的情况下,它会显而易见:

mysterious([], 0).
mysterious([X|Rest], Result) :-
    myst_1(Rest, X, Result).

myst_1([], Result, Result).
myst_1([_Y|Rest], X, Result) :-
    mysterious(Rest, Result1),
    Result is X + Result1.

你在问题​​中没有提到的一点是编译器必须在mysterious/2的最后一个句子中的 Y 上给你一个“单例变量”警告。这应该是已经发生的事情的强烈迹象。

答案 1 :(得分:2)

我可以通过评论来帮助你,也许你会更多地理解这个序言,让我们开始吧:

  

Prolog程序描述了通过条款定义的关系。 Pure Prolog仅限于Horn条款。有两种类型的条款:事实和规则。 (维基百科)

% comment in prolog starts with '%'
mysterious([],0).  % its called 'predicate', something like functions in imperative
                   % languages. it has two arguments: [], and 0. and it is ended
                   % by dot (.). Clauses with empty bodies are called facts. 
                   % (this is fact).

mysterious([X],X). % is actually a "rule" that says, "if the list has one element, 
                   % then the result is just that element". (by @mbratch)

mysterious([X,Y|Xs], Res) :- % now, when argument 1 is list which looks like
                             % [SomeElement, NextElement|LastElements],
  mysterious(Xs, Res1),      % call 'mysterious' with only LastElements 
                             % and variable Res1 (skip first two elements of list)
  Res is X + Res1.           % then add first element to Res1.

% it calculates the sum of every second element of list, beginning on first.