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

Stack overflow in Prolog DCG grammar rule: how to handle large lists efficiently or lazily

As a general remark you will find more on SO about it under the name library(pio). Also the way to use it cleanly is rather: :- use_module(library(pio)). Your example is way too complex, so I will only consider a slightly simpler case, a newline separated list of numbers: nats([]) –> []. nats([N|Ns]) –> nat(N), newline, … 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