问题
I am trying to use the split_string/4 predicate to turn a string into a list of strings. I want the string separated by each newline. This is what my code looks like
main(Argv) :-
[InputFilename|OutputFileName] = Argv,
read_file_to_string(InputFilename, InputFileString,[]),
split_string(InputFileString,"\n", "\n", InputFileList),
write(InputFileList).
But it is not writing anything to the console. However if I put
write(InputFileString)
It prints the contents of the file just fine. What am I doing wrong here?
回答1:
main(Input_filename,Output_filename) :-
read_file_to_string(Input_filename, Input_string,[]),
split_string(Input_string,"\n", "\n", Input_list),
write(Input_list).
Example input file C:/input_data.txt
Line one
Line two
Line three
Example run
?- main('C:/input_data.txt','C:/output_data.txt').
[Line one,Line two,Line three]
true.
Your use of |
in [InputFilename|OutputFileName]
is for separating the head and the tail of a list. A simple change to using ,
to pass in two parameters is all that is needed, e.g. main(Input_filename,Output_filename)
.
This answer also changed the style of the variable names to snake case which is customary with Prolog.
回答2:
If your Argv
is a list with two or more elements, it does not unify with [InputFilename|OutputFileName]
because this is not a list with two elements.
See:
$ swipl -q
?- [a,b] = [X|Y].
X = a,
Y = [b].
?- [a,b] = [X|Y], X = a, Y = b.
false.
If you know your list has exactly 2 elements, you can use [X, Y]
. If your list could have 2 or more elements, you can use [X, Y|_]
. Here:
?- [X,Y] = [a,b].
X = a,
Y = b.
?- [X,Y] = [a,b,c].
false.
?- [X,Y|_] = [a,b].
X = a,
Y = b.
?- [X,Y|_] = [a,b,c].
X = a,
Y = b.
?- [X,Y|_] = [a].
false.
来源:https://stackoverflow.com/questions/55465385/turning-a-text-file-into-a-list-using-prolog-using-the-split-string-predicate