如何将字符串转换为整数列表列表?

时间:2013-01-17 06:01:27

标签: prolog swi-prolog

我通过以下代码将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] ...]的最佳方法是什么?

此致!

1 个答案:

答案 0 :(得分: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]
    ).