SWI Prolog - Simplifying expressions

前端 未结 1 521
无人及你
无人及你 2021-01-15 21:49

I want to write a procedure simplify (E, E1) which is able to simplify expressions. I have only one operation +, and symbolic and numeric operands. Examples of this procedur

相关标签:
1条回答
  • 2021-01-15 22:31

    Well, this is obviously a homework question, but here's an SWI Prolog program anyway:

    :- op(500, xfy, user:(+)).
    
    simplify(Expr, Simplified) :-
      split(Expr, Syms0, Nums0),
      sumlist(Nums0, Nums),
      append(Syms0, [Nums], Syms),
      unparse(Syms, Simplified).
    
    split(X+Y, [X|Syms], Nums) :- atom(X), split(Y, Syms, Nums).
    split(X+Y, Syms, [X|Nums]) :- integer(X), split(Y, Syms, Nums).
    split(X, [X], [])          :- atom(X).
    split(X, [], [X])          :- integer(X).
    
    unparse([X], X).
    unparse([X|Xs], X+Y)       :- unparse(Xs, Y).
    
    :- simplify(a+1+b+5, a+b+6).
    :- simplify(1+b+9+a+5+c, b+a+c+15).
    
    0 讨论(0)
提交回复
热议问题