【问题标题】:prolog change show answer to print into list序言更改显示答案以打印到列表中
【发布时间】:2014-10-03 14:37:08
【问题描述】:

这是一段用于打印正方形的代码:

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).

运行后show_result([sq(1,2,'c'),sq(2,1,'A'),sq(2,2,'a'),sq(2,3,'C'),sq(3,2,'t')],3,3) 它会给出一个结果:

#c#
AaC
#t#

如何将结果存储到格式为:[[#,c,#],[A,a,C],[#t#]] 的列表中? 任何人都可以编写函数:show_result(Squares, MaxRow, MaxCol,result)? 非常感谢。

【问题讨论】:

  • 为什么是[#c#] 而不是[#,c,#]
  • 是的。你说的对。很抱歉错字错误。应该是[#,c,#]。你有什么办法找出问题所在吗?

标签: list printing prolog


【解决方案1】:

在描述列表时,请始终考虑使用 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, #]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多