Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The syntax error results from the fact that the first two clauses have no body.</p> <p>To answer your question, observe that the maximum of a list can be defined inductively as follows:</p> <ul> <li>The maximum of a list with one element is that element.</li> <li>The maximum of a list with multiple elements is the largest of the head and the maximum of the tail.</li> </ul> <p>Thus,</p> <pre><code>max_list([H], H). max_list([H|T], M2) :- max_list(T, M), M2 is max(H, M). </code></pre> <p>This code uses <code>max/2</code> (<a href="http://www.swi-prolog.org/pldoc/doc_for?object=max%2f2" rel="nofollow noreferrer">SWI-Prolog</a>, <a href="http://www.gprolog.org/manual/html_node/gprolog029.html" rel="nofollow noreferrer">GNU-Prolog</a>). Note that most or all Prolog implementations will have a built-in function <code>max_list/2</code> (<a href="http://www.swi-prolog.org/pldoc/doc_for?object=max_list%2f2" rel="nofollow noreferrer">S</a>, <a href="http://www.gprolog.org/manual/gprolog.html#htoc211" rel="nofollow noreferrer">G</a>), so there is actually no need to define it yourself.</p> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/questions/1816057/two-clause-definition-to-find-the-maximum-number-on-a-list/1816797#1816797">Bakore notes</a> that a tail recursive implementation may be more efficient. You can do this by defining a predicate <code>max_list/3</code> which takes an additional argument <code>C</code>, namely the largest value seen so far.</p> <pre><code>max_list([H|T], M) :- max_list(T, H, M). max_list([], C, C). max_list([H|T], C, M) :- C2 is max(C, H), max_list(T, C2, M). </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload