Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swi Prolog, Read file examples

I am new to Prolog but I get the basics. I am having problems reading a file. Here is my file:

16
78 45 12 32 457 97 12 5 731 2 4 55 44 11 999 7 

I want to read it so that I get back the characters as numbers. The first line is the amount of numbers on line 2. The problems are:

1) How to split them on SPACE or NEW LINE character

2) They must be numbers:32, not Strings: "32"

I am using SWI-Prolog.

like image 234
Dimitris Karagiannis Avatar asked Oct 17 '22 11:10

Dimitris Karagiannis


1 Answers

Here is my implementation:

my_read_file(File,Firt_Number ,List):-
    open(File, read, Stream),
    read_line(Stream, [Firt_Number]),
    read_line(Stream, List),
    close(Stream).

read_line(Stream, List) :-
    read_line_to_codes(Stream, Line),
    atom_codes(A, Line),
    atomic_list_concat(As, ' ', A),
    maplist(atom_number, As, List).

Example:

?- my_read_file("file.txt",N,L).
N = 16,
L = [78, 45, 12, 32, 457, 97, 12, 5, 731, 2, 4, 55, 44, 11, 999, 7] .
like image 188
coder Avatar answered Oct 21 '22 07:10

coder