prolog - 读取文件的一些问题
问题描述
我使用一些序言代码来读取要列出的文件编号,读取工作正常,我不能使用包含已读取编号的列表。
my_representation(Codes, Result) :-
atom_codes(Result, Codes).
stream_representations(Input, L) :-
read_line_to_codes(Input, Line),
( Line == end_of_file
-> L = []
;write("stream myrepresant oncesi Line="),writeln(Line),
write("stream myrepresant oncesi FinalLine="),writeln(FinalLine),
my_representation(Line, FinalLine),
stream_representations(Input, FurtherLines).
main :-
stream_representations(Input, L),
close(Input).
解决方案
实际上,调用stream_representations(Input, L)
将变量实例化为L
atom '1,2,3,4'
,如以下查询所示:
?- my_representation([49, 44, 50, 44, 51, 44, 52], L).
L = '1,2,3,4'.
为了获得所需的结果,您可以修改谓词my_representation
如下:
my_representation(Codes, Result) :-
atom_codes(Atom0, Codes), % obtain Atom0 = '1,2,3,4'
format(atom(Atom1), '[~w]', Atom0), % obtain Atom1 = '[1,2,3,4]'
read_term_from_atom(Atom1, Result, []). % transform atom '[1,2,3,4]' into list [1,2,3,4]
现在,我们有:
?- my_representation([49, 44, 50, 44, 51, 44, 52], L).
L = [1, 2, 3, 4].
[编辑]
您可以修改您的程序以使用这个新版本的谓词my_representation
,如下所示:
main :-
open('test.txt', read, Input),
stream_representations(Input, Codes),
close(Input),
my_representation(Codes, List), % <= call new version only here
writeln('list read': List),
forall(append(Prefix, Suffix, List),
writeln(Prefix - Suffix)).
stream_representations(Input, L) :-
read_line_to_codes(Input, Line),
( Line == end_of_file
-> L = []
; append(Line, FurtherLines, L), % <= just append line to further lines
stream_representations(Input, FurtherLines),
writeln('Stream represention': L) ).
my_representation(Codes, Result) :-
atom_codes(Atom0, Codes),
format(atom(Atom1), '[~w]', Atom0),
read_term_from_atom(Atom1, Result, []).
结果:
?- main.
Stream represention:[49,44,50,44,51,44,52]
list read:[1,2,3,4]
[]-[1,2,3,4]
[1]-[2,3,4]
[1,2]-[3,4]
[1,2,3]-[4]
[1,2,3,4]-[]
true.
推荐阅读
- parsing - 做块的野牛移位/减少冲突
- simultaneous - freeradius 用户连接限制
- python - 如何在没有任何空格的情况下计算熊猫中的令牌
- java - 为什么这个 ArrayList 'add' 操作不添加新元素?
- spring - 如何避免 Spring Boot Controller 捕获对 favicon 的请求?
- node.js - 特维利奥
到 Azure 连续语音转文本 - python - 如何使用 fastai unet_learner?
- java - XML 解析器 (Unmarshall) 使用 JaxB 从 xml 文件中获取元素
- html - 阻止 CKEditor 4 添加额外的 HTML 标签
- reactjs - 为什么我不断收到 TypeError: setScrollNav is not a function, when function is defined