Wednesday 15 August 2012

Number of occurrences of X in the List L in prolog -



Number of occurrences of X in the List L in prolog -

i trying find number of occurrences of x in list l eg :-

occurrences(a, [b, a, b, c, a, d, a], n ). n =3

my code not working .here code.

occ(k,l,n) :- n1=0, occ1(k,l,n1,n). occ1(k,[],n1,n) :- n=n1. occ1(k,l,n1,n) :- l=[x|l1], ( k=x -> n1 n1+1, occ1(k,l1,n1,n) ; occ1(k,l1,n1,n) ).

can tell me what's wrong in code.

while reply given @kay spot-on far fixing bug concerned, circumvents much bigger issue: code of occ1/4 logically impure.

this may not appear of import right now, using impure code has several negative consequences:

impure code cannot read declaratively, procedurally. debugging impure code tedious , pain-staking. impure predicates less "relational" pure counterparts. logical impurity hampers code re-use. because non-monotone, impure code prone lead logically unsound answers, particularly when working non-ground terms.

to show these problems persisted in code after having been "fixed" suggested @kay, allow consider "corrected" code , queries. first, here's corrected code:

occ(k,l,n) :- n1=0, occ1(k,l,n1,n). occ1(_,[],n1,n) :- n=n1. occ1(k,l,n1,n) :- l=[x|l1], ( k=x -> n2 n1+1, occ1(k,l1,n2,n) ; occ1(k,l1,n1,n) ).

here's query gave in question:

?- occ(a,[b,a,b,c,a,d,a],n). n = 3 ; false.

okay! if write query differently?

?- a=a,b=b,c=c,d=d, occ(a,[b,a,b,c,a,d,a],n). = a, b = b, c = c, d = d, n = 3 ; false.

okay! if reorder goals? logical conjunction should commutative...

?- occ(a,[b,a,b,c,a,d,a],n), a=a,b=b,c=c,d=d. false.

fail! seemed occ1/4 fine, reply logically unsound.

this can avoided using logically pure code: @ pure , monotone code gave in my answer related question "prolog - count repititions in list (sic)".

prolog

No comments:

Post a Comment