List 序言更改显示要打印到列表中的答案
下面是一段用于打印方块的代码:List 序言更改显示要打印到列表中的答案,list,printing,prolog,List,Printing,Prolog,下面是一段用于打印方块的代码: show_result(Squares,MaxRow,MaxCol) :- show_result(Squares,MaxRow,MaxCol,1), nl. show_result(_,MaxRow,_,Row) :- Row > MaxRow, !. show_result(Squares,MaxRow,MaxCol,Row) :- show_result(Squares,MaxRow,MaxCol,Row,1), nl, Row1
show_result(Squares,MaxRow,MaxCol) :-
show_result(Squares,MaxRow,MaxCol,1), nl.
show_result(_,MaxRow,_,Row) :- Row > MaxRow, !.
show_result(Squares,MaxRow,MaxCol,Row) :-
show_result(Squares,MaxRow,MaxCol,Row,1), nl,
Row1 is Row+1, show_result(Squares,MaxRow,MaxCol,Row1).
show_result(_,_,MaxCol,_,Col) :- Col > MaxCol, !.
show_result(Squares,MaxRow,MaxCol,Row,Col) :-
(memberchk(sq(Row,Col,X),Squares), !, write(X); write('#')).
Col1 is Col+1, show_result(Squares,MaxRow,MaxCol,Row,Col1).
运行后显示结果[sq1,2,'c',sq2,1,'A',sq2,2,'A',sq2,3,'c',sq3,2,'t'],3,3,3
它将给出一个结果:
#c#
AaC
#t#
如何将结果存储到格式为:[,c,],[a,a,c],[t]]的列表中?
任何人都可以编写函数:show_resultSquares、MaxRow、MaxCol、result?
非常感谢。 < P>当描述一个列表时,总是考虑使用DCG。在您的情况下,只需对代码进行一些简单的修改,就可以很容易地获得所需的内容:
show_result(Squares,MaxRow,MaxCol, List) :-
phrase(show_result(Squares,MaxRow,MaxCol,1), List).
show_result(_,MaxRow,_,Row) --> { Row > MaxRow }, !.
show_result(Squares,MaxRow,MaxCol,Row) -->
{ phrase(show_result(Squares,MaxRow,MaxCol,Row,1), Line) } ,
[Line],
{ Row1 is Row+1 },
show_result(Squares,MaxRow,MaxCol,Row1).
show_result(_,_,MaxCol,_,Col) --> { Col > MaxCol }, !.
show_result(Squares,MaxRow,MaxCol,Row,Col) -->
( { memberchk(sq(Row,Col,X),Squares) } ->
[X]
; [#]
),
{ Col1 is Col+1 },
show_result(Squares,MaxRow,MaxCol,Row,Col1).
示例查询及其结果:
?- show_result([sq(1,2,'c'),sq(2,1,'A'),sq(2,2,'a'),sq(2,3,'C'),sq(3,2,'t')], 3, 3, List).
List = [[#, c, #], ['A', a, 'C'], [#, t, #]]
为什么是[c]而不是[c],是的。你是对的。对不起,错了。应该是[,c,]你有什么办法解决这个问题吗?