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

Faster implementation of verbal arithmetic in Prolog

Consider using finite domain constraints, for example, in SWI-Prolog: :- use_module(library(clpfd)). puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :- Vars = [S,E,N,D,M,O,R,Y], Vars ins 0..9, all_different(Vars), S*1000 + E*100 + N*10 + D + M*1000 + O*100 + R*10 + E #= M*10000 + O*1000 + N*100 + E*10 + Y, M #\= 0, S #\= 0. … 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

Most general higher-order constraint describing a sequence of integers ordered with respect to a relation

Hoogle was not very useful, but Hayoo is! foldcmpl so this is a special form of fold for a list, but it does not apply length list times but one time less. isSortedBy is not entirely general in its name, but in its signature. Maybe insisting on the most general name is not that helpful. … Read more

tech