Segregating Lists in Prolog

A logically pure implementation is very straight-forward, thanks to clpfd: :- use_module(library(clpfd)). list_evens_odds([],[],[]). list_evens_odds([X|Xs],[X|Es],Os) :- X mod 2 #= 0, list_evens_odds(Xs,Es,Os). list_evens_odds([X|Xs],Es,[X|Os]) :- X mod 2 #= 1, list_evens_odds(Xs,Es,Os). Some sample queries we expect to succeed (with a finite sequence of answers): ?- Xs = [1,2,3,4,5,6,7], list_evens_odds(Xs,Es,Os). Xs = [1,2,3,4,5,6,7], Es = [ 2, 4, … Read more

Explanation of a Prolog algorithm to append two lists together

First, let’s translate the clauses into something more understandable: append([], List, List) :- !. can be written append([], List2, Result) :- Result = List2, !. and append([H|L1], List2, [H|L3]) :- append(L1, List2, L3). can be written append(List1, List2, Result) :- List1 = [Head1 | Tail1], Result = [HeadR | TailR], Head1 = HeadR, append(Tail1, List2, … Read more

Get elements from list of lists

You asked for all elements of a list of lists. That is, for [[1,2,3],[4]] this would be the list [1,2,3,4]. However, for [[[1],[3]]] this would be the list [[1],[3]] since [1] and [3] are elements. For this reason, flatten/2 is incorrect it gives you [1,3] as an answer. Also, for 1 it gives [1]… Here … Read more

Subsets in Prolog

Here goes an implementation: subset([], []). subset([E|Tail], [E|NTail]):- subset(Tail, NTail). subset([_|Tail], NTail):- subset(Tail, NTail). It will generate all the subsets, though not in the order shown on your example. As per commenter request here goes an explanation: The first clause is the base case. It states that the empty list is a subset of the … Read more

Read a file line by line in Prolog

You can use read to read the stream. Remember to invoke at_end_of_stream to ensure no syntax errors. Example: readFile.pl main :- open(‘myFile.txt’, read, Str), read_file(Str,Lines), close(Str), write(Lines), nl. read_file(Stream,[]) :- at_end_of_stream(Stream). read_file(Stream,[X|L]) :- \+ at_end_of_stream(Stream), read(Stream,X), read_file(Stream,L). myFile.txt ‘line 0’. ‘line 1’. ‘line 2’. ‘line 3’. ‘line 4’. ‘line 5’. ‘line 6’. ‘line 7’. ‘line … Read more

Remove duplicates in list (Prolog)

You are getting multiple solutions due to Prolog’s backtracking. Technically, each solution provided is correct, which is why it is being generated. If you want just one solution to be generated, you are going to have to stop backtracking at some point. This is what the Prolog cut is used for. You might find that … Read more

Complexity of ISO Prolog predicates

tl;dr: No and no. Let’s start with sort/2 which ideally would need n ld(n) comparisons. Fine, but how long does one comparison take? Let’s try this out: tails(Es0, [Es0|Ess]) :- Es0 = [_|Es], tails(Es, Ess). tails([],[[]]). call_time(G,T) :- statistics(runtime,[T0|_]), G, statistics(runtime,[T1|_]), T is T1 – T0. | ?- between(12,15,I), N is 2^I, length(L,N),maplist(=(a),L), tails(L,LT), call_time(sort(LT,LTs), … Read more