2013-01-17 187 views
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] ...]?

真誠!

回答

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] 
    ). 
+0

不熟悉的DCG,但你的代碼工作。謝謝! –

相關問題