> rules.pl: > product([], []). > product([L1Head|L1Tail], [L2First|[L2Second|L2Tail]]) :- L1Head is L2First * > L2Second, iloczyn(L1Tail, L2Tail).
“iloczyn” should be “product”. > 1. my first attempt in the first goal was: > L1Head = L2First * L2Second, which apparently isn't true. Why doesn't it > work? Why do I need the 'is' word there? It looks like prolog doesn't > compute the value before unification, but why? Because operators are term constructors, not arithmetic operations. A * B is therefore the term with the root node “*” and the variables A and B as sub-terms. The meaning of “multiplication” for the “*” operator is given by the “is” predicate as in “X is Term”, which evaluates its right operand Term as an arithmetic expression and unifies the result with its left operand X.. You may take a look to the answers of the following Stack Overflow question. http://stackoverflow.com/questions/1417253/prolog-operator > 2. When I rewrite the program so: > product([], []). > product(L1, L2) :- [L1Head|L1Tail] = L1, [L2First|[L2Second|L2Tail]] = L2, > L1Head is L2First * L2Second, product(L1Tail, L2Tail). Since there are two clauses to define “product”, executing this predicate introduces a choice between the two clauses: when you execute product([], []), the first choice succeeds (therefore the top-level says “true”), but there remains the second choice, so Prolog asks you if you want to continue and explore it as well. Of course, since in the second choice, L1 = [], it cannot succeed. However, GNU Prolog does “first argument head indexing”: clauses whose heads have a term as first argument are compiled with a more efficient selection than trying all the clauses. When the first argument of the call is instantiated, this selection directly branches to the clauses whose first term carry the matching head constructor. -- Thierry. _______________________________________________ Users-prolog mailing list [email protected] https://lists.gnu.org/mailman/listinfo/users-prolog
