SWI Prolog - 简化表达式 [英] SWI Prolog - Simplifying expressions

查看:51
本文介绍了SWI Prolog - 简化表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个能够简化表达式的过程simple (E, E1).我只有一个操作+,以及符号和数字操作数.此过程的示例:

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 procedure:

simplify(a + 1 + b + 5, E)  ------>  E = a + b + 6

simplify(1 + b + 9 + a + 5 + c, E) ------>  E = b + a + c + 15

我们转移到开头的所有字符.然后我们计算数值操作数的总和并将其附加到表达式的末尾.

All the characters we shift to the beginning. Then we calculate the sum of numerical operands and appends it to the end of the expression.

如何编写程序?

推荐答案

好吧,这显然是一个家庭作业问题,但无论如何这里有一个 SWI Prolog 程序:

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

这篇关于SWI Prolog - 简化表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆