Explain what this prolog program does?
I am working on Prolog and I came across the below program. When I execute this program with a query for example: mysterious([2,3,4,5,6,7,8],L). It has given me the answer 20. I did not understand the flow of getting this result. can anyone help me to understand this code?...How does it produce the answer 20 for the above mentioned query?
mysterious(,0). mysterious([X],X). mysterious([X,Y|Xs], Res) :- mysterious(Xs, Res1), Res is X + Res1.
Because this is such a basic program, I will give you a hint. First off, this:
foo(). foo([X]). foo([X,Y|Rest]) :- foo(Rest).
could be also written as:
foo(). foo([First|Rest]) :- bar(Rest, First). bar(, Last). bar([This|Rest], Prev) :- foo(Rest).
It is unnecessarily verbose, but more explicit. In your case, however, it makes something obvious:
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.
Something which you did not mention in your question is that the compiler must have given you a "singleton variable" warning on the Y in the last clause of mysterious/2. This should have been a strong indication of what is going on already.
I can help you by commenting lines, maybe you will understand the prolog a little more, let's start:
Prolog programs describe relations, defined by means of clauses. Pure Prolog is restricted to Horn clauses. There are two types of clauses: facts and rules. (by wikipedia)
% 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.