|Subject:||Re: prolog newbie - basic questions to a (self) written program|
|Date:||Thu, 31 Jan 2013 22:44:22 +0100|
> rules.pl:“iloczyn” should be “product”.
> product(, ).
> product([L1Head|L1Tail], [L2First|[L2Second|L2Tail]]) :- L1Head is L2First *
> L2Second, iloczyn(L1Tail, L2Tail).
> 1. my first attempt in the first goal was:Because operators are term constructors, not arithmetic operations.
> 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?
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.
> 2. When I rewrite the program so:Since there are two clauses to define “product”, executing this
> product(, ).
> product(L1, L2) :- [L1Head|L1Tail] = L1, [L2First|[L2Second|L2Tail]] = L2,
> L1Head is L2First * L2Second, product(L1Tail, L2Tail).
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.
|[Prev in Thread]||Current Thread||[Next in Thread]|