问题
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,"_","_"]
"_" 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).
I will get something like
X = [_G1426, _G1429, _G1432, 9, _G1438, _G1441].
I know if I define a predicate
pred(a,[_,_,_,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?
回答1:
to_var_list([],[]).
to_var_list([A|R1],[B|R2]):-
(A = '_' ->
true;
A = B),
to_var_list(R1,R2).
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.
来源:https://stackoverflow.com/questions/26128338/prolog-how-to-make-a-variable-list-out-of-a-given-list-from-input-file