Prolog getting head and tail of string

SWI-Prolog has several different representation of what you might call “strings”. List of character codes (Unicode); List of chars (one-letter atoms); Strings, which are “atomic” objects, and can be manipulated only with the built-in predicates for strings; And finally, of course, atoms. You should read the documentation, but for now, you have at least two … Read more

Recursive Prolog predicate for reverse / palindrome

Ad 1: It is impossible to define reverse/2 as a (directly edit thx to @repeat: tail) recursive predicate – unless you permit an auxiliary predicate. Ad 2: palindrome(X) :- reverse(X,X). But the easiest way is to define such predicates with DCGs: iseq([]) –> []. iseq([E|Es]) –> iseq(Es), [E]. reverse(Xs, Ys) :- phrase(iseq(Xs), Ys). palindrome(Xs) :- … 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

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

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