我是Prolog的新来者,我不明白在练习中如何做到这一点:
如果我在SWI-prolog中使用以下命令,它将显示特殊的变量,如_G373。
14 ?- write([[_,_,_,_],[_,_,_,#],[_,_,_,_]]).
[[_G403,_G406,_G409,_G412],[_G418,_G421,_G424,#],[_G433,_G436,_G439,_G442]]
true.
但是在.pl文件中,如果我从文件中读取相同的列表列表并将它们存储在Puzzle中,
read_file(Filename, Content) :- %read file using read lines
open(Filename, read, Stream), %open a file, start read stream
read_lines(Stream, Content), %using readlines store content from stream into content
close(Stream). %Close the stream
read_lines(Stream, Content) :- %read lines from read a single line
read_line(Stream, Line, Last), %using read_line
( Last = true %if last = ture, means read to the file end, make line = [], content = []
-> ( Line = [] %else make content = [line]
-> Content = []
; Content = [Line]
)
; Content = [Line|Content1], %store the lines from up to bottom
read_lines(Stream, Content1)
).
read_line(Stream, Line, Last) :- %read line from read a character
get_char(Stream, Char), %
( Char = end_of_file %if read to the file end, make line = [], last = true
-> Line = [], %else if read to the line's end, make line[], last = false
Last = true
; Char = '\n'
-> Line = [],
Last = false
; Line = [Char|Line1],
read_line(Stream, Line1, Last)
). %else store the character in order, just for one line
我用的时候
write('Puzzle'),nl,write(Puzzle),nl.
,它只显示
Puzzle
[[_,_,_,_],[_,_,_,#],[_,_,_,_]]
如何将这些_更改为特殊变量,如SWI-Prolog?
感谢。
答案 0 :(得分:1)
不太清楚你想要实现的目标和原因。您可以使用read_term
来阅读有效的Prolog术语。所以,如果你实际上有一个包含以下内容的文件,名为test.pl
:
[[_,_,_,_],[_,_,_,#],[_,_,_,_]].
然后,从顶层开始,您可以:
?- open('test.pl', read, In), read_term(In, T, []), close(In).
In = <stream>(0x1c71e10),
T = [[_4826, _4832, _4838, _4844], [_4856, _4862, _4868, #], [_4886, _4892, _4898, _4904]].
这似乎就是你追求的目标?
请注意,您正在阅读的文件中的列表后面有一个句号。