Counting in a Prolog List -


i'm trying make prolog function (i know it's not function can't recall it's name) given list , number n returns list elements repeat @ least n times.

xpto(['a', 'a', 'a', 'b', 'b', 'c'], out, 3) should return out = ['a']

xpto(['a', 'a', 'a', 'b', 'b', 'c'], out, 2) should return out = ['a', 'b']

etc.

i have:

xpto([], _, _).  xpto([h | l], o, num) :-     count(h, [h | l], n),     n = num,     xpto(l, [h | o], num).  xpto([h | l], o, num) :-     count(h, [h | l], n),     n \= num,     xpto(l, o, num). 

where in count(a, l, n) n number of times repeats in l, doesn't work. i'm pretty sure algorithm works on paper.

any appreciated :)

if prolog system supports , use following implementation of xpto/3. implementation preserves !

let's implement xpto/3 based on list_counts/2, meta-predicates tfilter/3 , maplist/3, , on (#=<)/3. (#=<)/3 reified version of constraint (#=</2).

:- use_module(library(clpfd)). :- use_module(library(lambda)).  xpto(xs,ys,n) :-    list_counts(xs,css0),    tfilter(n+\ (_-v)^(n #=< v),css0,css1),    maplist(\ (k-_)^k^true,css1,ys). 

let's run queries gave in questions:

 ?- xpto([a,a,a,b,b,c],out,3). out = [a].                        % succeeds deterministically  ?- xpto([a,a,a,b,b,c],out,2). out = [a,b].                      % succeeds deterministically 

as code used in implementation monotone, can ask quite general queries , still logically sound answers:

?- xpto([a,a,a,b,b,c],out,n). out = [],      n in 4..sup ; out = [a],     n = 3       ; out = [a,b],   n = 2       ; out = [a,b,c], n in inf..1 . 

now answers if first argument contains variables?

?- xs = [_,_],xpto(xs,out,n). xs = [_a,_a], out = [],       n in 3..sup             ; xs = [_a,_a], out = [_a],     n in inf..2             ; xs = [_a,_b], out = [],       n in 2..sup, dif(_a,_b) ; xs = [_a,_b], out = [_a, _b], n in inf..1, dif(_a,_b) . 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -