Prolog - How to make a variable list out of a given list from input file?

久未见 提交于 2019-12-20 06:27:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!