reversible “binary to number” predicate

Use CLP(FD) constraints, for example: :- use_module(library(clpfd)). binary_number(Bs0, N) :- reverse(Bs0, Bs), foldl(binary_number_, Bs, 0-0, _-N). binary_number_(B, I0-N0, I-N) :- B in 0..1, N #= N0 + B*2^I0, I #= I0 + 1. Example queries: ?- binary_number([1,0,1], N). N = 5. ?- binary_number(Bs, 5). Bs = [1, 0, 1] . ?- binary_number(Bs, N). Bs = … Read more

Splitting a list of integers into a list of positive integers and a list of negative integers

The recursive part is not quite correct. split([], [], []). split([Head|Tail], [Head|List1], List2) :- Head>=0, split(Tail, List1, List2). split([Head|Tail], List1, [Head|List2]) :- Head<0, split(Tail, List1, List2). The Head should be added to the positive list if Head >= 0 and to the negative list when Head < 0. Moreover, checking the sign of Head at … 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

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