0

我通过以下代码将 X = [[1,2,3,4,5,6],[6,5,4,3,2,1]|...] 写入文件:

?-tell('test.txt'),maplist(format('~d ~d ~d ~d ~d ~d ~n'),X),told.

$cat test.txt
1 2 3 4 5 6
6 5 4 3 1 1
...

并使用以下代码恢复它:

?-open("test.txt",read,F),read_stream_to_codes(F,N),write(N),close(F).
N = [49, 50, 51, 52, 53, 54 ...]

将 N 转换为 [[1,2,3,4,5,6],[6,5,4,3,2,1]...] 的最佳方法是什么?

真挚地!

4

1 回答 1

1

我会一次做一行:

:- use_module(library(dcg/basics)).

ints(L) --> blanks, (integer(I), ints(Is), {L = [I|Is]} ; {L = []}).

read_ints(F, L) :-
    open(F, read, S),
    file_ints(S, L),
    close(S).

file_ints(S, L) :-
    read_line_to_codes(S, Cs),
    (   Cs == end_of_file
    ->  L = []
    ;   phrase(ints(Is), Cs),
        file_ints(S, R),
        L = [Is|R]
    ).
于 2013-01-17T09:08:49.567 回答