我有与formatting the output with proper paranthesis - Prolog相同的问题,但是解决方案不应该使用!
和-->
。来自链接的接受答案包含这两个运算符。特别是,我正在寻找一种在规则参数上使用Prolog模式匹配的解决方案。
为了方便起见,我在这里重写这个问题。
这个问题与first order logic creating terms for arithmetic expressions using prolog直接相关。在按照链接实现逻辑后,我对printauth/1
的输出格式有问题。它目前的结果是8-2+4* -3
,怎么可能得到像((8-2)+(4* -3))
这样的东西(请注意,它与+(-(8,2),*(4,-3)))
不同。
我一直在尝试在format/2
谓词中使用各种选项(\k,\q)
,但都不起作用。即使我尝试了write_canonical
和其他写谓词,仍然没有成功。
我知道我不能修改输出,因为有=..
谓词。
arithmetic_operator(plus, +).
arithmetic_operator(minus, -).
arithmetic_operator(times, *).
arithmetic_expression(N, N) :- integer(N).
arithmetic_expression(Term, Expr) :-
Term =.. [Functor,Component1,Component2],
arithmetic_operator(Functor, Operator),
arithmetic_expression(Component1, Expr1),
arithmetic_expression(Component2, Expr2),
Expr =.. [Operator, Expr1, Expr2].
printterm(Term) :- arithmetic_expression(Term, Expr), format("(~w\n)",[Expr]).
电流输出
?- printterm(plus((minus(8,2)),(times(4,3)))).
(8-2+4*3)
true .
预期输出
?- printterm(plus((minus(8,2)),(times(4,3)))).
((8-2)+(4*3))
true .
发布于 2020-11-03 04:24:49
我不认为像这样专注于I/O是正确的方法。链接答案将括号表达式构建为数据结构,它可以使用DCG( -->
规则)等出色的功能。
也就是说,如果有必要,您可以像在任何其他编程语言中一样,在Prolog中打印带全括号的表达式:使用递归。
print_term(Term) :-
arithmetic_expression(Term, Expr),
print_expr(Expr),
nl.
print_expr(N) :-
integer(N),
write(N).
print_expr(Expr) :-
Expr =.. [Operator, Left, Right],
write('('),
print_expr(Left),
write(Operator),
print_expr(Right),
write(')').
?- print_term(plus((minus(8,2)),(times(4,3)))).
((8-2)+(4*3))
true ;
false.
https://stackoverflow.com/questions/64643481
复制相似问题