Swi Prolog, Read Sample Files

I'm new to Prolog, but I have the basics. I'm having trouble reading the 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 in order to return characters as numbers. The first line is the number of numbers in line 2. Problems:

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

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

I am using SWI-Prolog.

+3


source to share


1 answer


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

      

+3


source







All Articles