列表列表转换为修改后的单个列表 [英] List of lists into modified single list
问题描述
这些是从输入文件中读取的谓词
These are predicates which reads from input file
read_line(L,C) :-
get_char(C),
(isEOFEOL(C), L = [], !;
read_line(LL,_),% atom_codes(C,[Cd]),
[C|LL] = L).
%Tests if character is EOF or LF.
isEOFEOL(C) :-
C == end_of_file;
(char_code(C,Code), Code==10).
read_lines(Ls) :-
read_line(L,C),
( C == end_of_file, Ls = [] ;
read_lines(LLs), Ls = [L|LLs]
).
输入文件:
A B
C D
E F
G H
read_lines(L)
返回 L = [[A, ,B],[C, ,D],[E, ,F],[G, ,H]]代码>.我的目标是替换所有空格并将列表列表合并为单个列表.所以预期的输出应该是这样的:
L = [A-B,C-D,E-F,G-H]
.到目前为止我得到的是修改 read_line
函数:
read_lines(L)
returns L = [[A, ,B],[C, ,D],[E, ,F],[G, ,H]]
. My goal is to replace all the spaces and merge list of lists into single list. So expected output should look like: L = [A-B,C-D,E-F,G-H]
.
What I got so far is modified read_line
function:
read_line(L,C) :-
get_char(C),
( (char_code(C,Code), Code == 32)
-> C = '-'
; C = C),
(isEOFEOL(C), L = [], !;
read_line(LL,_),% atom_codes(C,[Cd]),
[C|LL] = L).
当我使用它时,Prolog 说 Syntax error: Unexpected end of file
.这有什么问题?
When I use it, Prolog says Syntax error: Unexpected end of file
. What's wrong with that?
推荐答案
问题出在这段代码中:
( (char_code(C,Code), Code == 32)
-> C = '-'
; C = C),
如果一个空格字符被读入变量 C
,char_code
将 Code
绑定到 32,条件为真.然后Prolog 尝试将C
与'-'
统一起来,但是C
已经绑定到' '
!这失败了,因此您的 read_line
调用失败并在标准输入流上留下一些未使用的输入.下次 Prolog 尝试从您那里读取输入时,它实际上会读取剩余的输入.
If a space character was read into variable C
, char_code
binds Code
to 32, and the condition is true. Then Prolog tries to unify C
with '-'
, but C
is already bound to ' '
! This fails, so your read_line
call fails and leaves some unconsumed input on the standard input stream. The next time Prolog tries to read input from you, it actually reads that remaining input.
问题的根本原因是您似乎试图重新分配"变量 C
.这在 Prolog 中是不可能的;一旦一个变量被绑定,它只能在回溯时解除绑定.
The underlying cause of the problem is that you seem to be trying to "reassign" the variable C
. That is not possible in Prolog; once a variable is bound, it can only become unbound on backtracking.
使用 new 变量,如下所示:
Use a new variable, something like this:
( (char_code(C,Code), Code == 32)
-> NewC = '-'
; NewC = C),
在适当的地方使用 NewC
.
这篇关于列表列表转换为修改后的单个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!