Prolog – count repetitions in list

This answer shows a logically pure way to do it. The following is based on clpfd. :- use_module(library(clpfd)). We define meta-predicate tcount/3 similarly to tfilter/3! :- meta_predicate tcount(2,?,?). tcount(P_2,Xs,N) :- N #>= 0, list_pred_tcount_(Xs,P_2,0,N). :- meta_predicate list_pred_tcount_(?,2,?,?). list_pred_tcount_([] , _ ,N ,N). list_pred_tcount_([X|Xs],P_2,N0,N) :- if_(call(P_2,X), (N1 is N0+1, N1 #=< N), N1 = N0), list_pred_tcount_(Xs,P_2,N1,N). … Read more

Finding Unique Items in a List

You have been using cut and an unsafe form of negation. Both have to be used with extreme care. An immediate fix would be to guard your program against uses it is not designed for: unique(X, Xs) :- iwhen(ground(X+Xs), your_unique(X, Xs)). This uses iwhen/2 which is similar to when/2 except that it does not delay: … Read more

Prolog successor notation yields incomplete result and infinite loop

If you want to study termination properties in depth, programs using successor-arithmetics are an ideal study object: You know a priori what they should describe, so you can concentrate on the more technical details. You will need to understand several notions. Universal termination The easiest way to explain it, is to consider Goal, false. This … Read more

Delete vowels in a list

The following is based on the reification of term equality/inequality. First, we first define list_memberd_t/3, which behaves just like the memberd_truth/3 but has a different argument order: list_memberd_t([] ,_,false). list_memberd_t([Y|Ys],X,Truth) :- if_(X=Y, Truth=true, list_memberd_t(Ys,X,Truth)). list_memberd_truth(Xs,X,Truth) :- list_memberd_t(Xs,X,Truth). For the sake of brevity, let’s define memberd_t/3 based on list_memberd_t/3: memberd_t(X,Xs,Truth) :- list_memberd_t(Xs,X,Truth). As a parallel to … Read more