Prolog-如何从输入文件的给定列表中制作变量列表? [英] Prolog - How to make a variable list out of a given list from input file?
问题描述
我有一个输入谓词,它将文件作为列表读取:input(Filename,List).然后,该列表将采用
I have a input predicate will read the file as a list: input(Filename,List). The list then will be in the format of
["_","_","_",9,"_","_"]
"_"
此处实际上是下划线"_"
的字符,而不是通配符.问题是如何编写谓词pred(List,List2),然后将所有"_"
转换为变量,但将9
保持在同一位置?因此,如果我输入
"_"
is literally the character underscore "_"
here, not a wild card. The question is how can I write a predicate pred(List,List2) then transform all the "_"
into variables but keep 9
still at the same position? So If I type in
input(Filename,List),pred(List,X).
我会得到类似的东西
X = [_G1426, _G1429, _G1432, 9, _G1438, _G1441].
我知道我是否定义谓词
pred(a,[_,_,_,9,_,_]).
然后通过调用pred(a,X)
我可以得到类似的结果.但是问题是如何使其适应所有类型的输入列表,9
可能在另一个位置,或者列表的大小可能不同.有人可以帮我吗?
Then by calling pred(a,X)
I can have the similar result. But the thing is how to make it adaptive to all kinds of input lists, 9
might be at a another position or the list might be of different size. Can somebody help me?
推荐答案
to_var_list([],[]).
to_var_list([A|R1],[B|R2]):-
(A = '_' ->
true;
A = B),
to_var_list(R1,R2).
如果您实际上只有一个字符串而不加下划线原子,则将'_'
与"_"
交换.
另外,有一个read
谓词可以实现您想要实现的功能,但是在文件中的列表后面需要一个.
.
Exchange '_'
with "_"
if you actually have one character strings and not underscore atoms.
Also, there is a read
predicate that does something like you want to achieve, but it expects a .
after your lists in the file.
这篇关于Prolog-如何从输入文件的给定列表中制作变量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!