5
votes

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.

1
I have seen this post and it doesn't help. the first answer returns character codes but i want numbers. The other one gives me an error. I need the number available to me in a list or something so i can process them laterDimitris Karagiannis

1 Answers

3
votes

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] .