read numbers from file in prolog and sorting

2019-04-17 05:00发布

问题:

how to read numbers from file and sorting that in (prolog programming)

回答1:

You can first try the following, reading multiple lines from the console:

?- repeat, read(X), (X==end_of_file, !, fail; true).
1.
X = 1 ;
2.
X = 2 ;

No

Explanation: The repeat/0 predicate repeatedly succeeds so that read/1 is called over and over. Calling read/1 only stops when end_of_file has been reached because of the cut that follows it.

Then you can wrap it into a findall/3 and call sort/2:

?- findall(X,(repeat, read(X), (X==end_of_file, !, fail; true)),L), sort(L,R).
2.
1.

L = [2, 1],
R = [1, 2]

If needed you can use your own sort and enhance the read by a stream argument.

Best Regards

(c) 2010, Jan Burse, 8004 Zürich



标签: prolog