我是 Prolog 的新手,但我掌握了基础知识。我在读取文件时遇到问题。这是我的文件:
16
78 45 12 32 457 97 12 5 731 2 4 55 44 11 999 7
Run Code Online (Sandbox Code Playgroud)
我想阅读它,以便将字符作为数字取回。第一行是第2行的数字数量,问题是:
1) 如何在空格或新行字符上拆分它们
2)它们必须是数字:32,而不是字符串:“32”
我正在使用 SWI-Prolog。
这是我的实现:
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).
Run Code Online (Sandbox Code Playgroud)
例子:
?- 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] .
Run Code Online (Sandbox Code Playgroud)