Safer type tests in Prolog

The testing for types needs to distinguish itself from the traditional “type testing” built-ins that implicitly also test for a sufficient instantiation. So we effectively test only for sufficiently instantiated terms (si). And if they are not sufficiently instantiated, an appropriate error is issued. For a type nn, there is thus a type testing predicate … Read more

Prolog: Filtering a list?

SWI-Prolog offers exclude/3 and other such meta-predicates. Your original problem can be coded like this: are_identical(X, Y) :- X == Y. filterList(A, In, Out) :- exclude(are_identical(A), In, Out). Usage example: ?- filterList(A, [A, B, A, C, D, A], Out). Out = [B, C, D].

Einsteins Riddle Prolog

This site is devoted to solve such puzzles with CLP(FD). But the full power of CLP(FD) is overkill here: your assignment can be solved effectively searching the entire solution space when you have adequately described the constraints. The solution will be composed of 5 houses, where each attribute satisfy all constraints imposed by description. Be … Read more

Using a constrained variable with `length/2`

What’s probably more useful than a slightly less nondeterministic length/2 is a proper list-length constraint. You can find an ECLiPSe implementation of it here, called len/2. With this you get the following behaviour: ?- N :: 1..3, len(Xs, N). N = N{1 .. 3} Xs = [_431|_482] % note it must contain at least one … Read more

Flatten a list in Prolog

The definition of flatten2/2 you’ve given is busted; it actually behaves like this: ?- flatten2([a, [b,c], [[d],[],[e]]], R). R = [a, b, c] ; false. So, given the case where you’ve already bound R to [a,b,c,d,e], the failure isn’t surprising. Your definition is throwing away the tail of lists (ListTail) in the 3rd clause – … Read more

Find powers of 2 in a list Prolog

Here’s how you can find the “powers of two” in logically-pure way! Using sicstus-prolog 4.3.5, library(reif) and library(clpz): :- use_module([library(reif), library(clpz)]). power_of_two_t(I, T) :- L #= min(I,1), M #= I /\ (I-1), call((L = 1, M = 0), T). % using (=)/3 and (‘,’)/3 of library(reif) Sample query1 using meta-predicate tfilter/3 in combination with power_of_two_t/2: … Read more

Prolog removing unique elements only

Prolog rules are read independently of each other, so you need one rule for the case where the element is unique and one where it is not. Provided the order of the elements is not relevant, you might use: ?- remUniqueVals([A,B,C], [1,1]). A = B, B = 1, dif(C, 1) ; A = C, C … Read more