this trivial implementation of function returns length of list in prolog
count([], 0). count([_|b], t) :- count(b, u), t u + 1.
one thing prolog still cannot wrap head around flexibility of using variables parameters.
so example can run count([a, b, c], 3).
, true
. can run count([a, b], x).
, answer x = 2.
. oddly (at least me) can run count(x, 3).
, @ least 1 result, looks x = [_g4337877, _g4337880, _g4337883] ;
before interpreter disappears infinite loop. can run "flexible" count(x, a).
, x = [], = 0 ; x = [_g4369400], = 1.
, incomplete somehow nice.
therefore multifaceted question. can somehow explain prolog not beyond first result when executing count(x, 3).
? can somehow make prolog generate number of solutions count(x, a).
? there limitation of kind of solutions can generate? specific predicate, prevents me generating solutions possible kinds of queries?
this trivial implementation
depends viewpoint: consider
count(l,c) :- length(l,c).
shorter , functional. , 1 works use case.
edit
library clp(fd) allows for
:- use_module(library(clpfd)). count([], 0). count([_|b], t) :- u #>= 0, t #= u + 1, count(b, u). ?- count(x,3). x = [_g2327, _g2498, _g2669] ; false.
(further) answering comments
it sarcasm
no, sorry giving impression. attempt give synthetic answer question. every details of implementation of length/2 - indeed longer code - have been weighted give general , efficient building block.
there must general concept
i call (full) prolog such general concept. start, prolog requires solve computational tasks describing relations among predicate arguments. once have described our relations, can query our 'knowledge database', , prolog attempts enumerate all answers, in specific order.
high level concepts unification , depth first search (backtracking) keys in model.
now, think you're looking second order constructs var/1, allow reason about our predicates. such constructs cannot written in (pure) prolog, , growing school of thinking requires avoid them, because rather difficult use. posted alternative using clp(fd), shields in some situation. in question specific context, give simple , elegant solution.
i not trying re-implement length
well, i'm aware of this, since count/2 aliases length/2, why not study reference model ? ( swi-prolog site used have browsable source, seems it's broken right )
Comments
Post a Comment