如何在prolog中进行算术表达式评估? [英] How to do arithmetic expression evaluation in prolog?

查看:63
本文介绍了如何在prolog中进行算术表达式评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决 prolog 中的算术表达式(实现 - eclipse prolog).要解决的算术表达式是这样的:

I am trying to solve an arithmetic expression in prolog (implementation - eclipse prolog). The arithmetic expression to be solved is like this:

A * (C + B * X) + D * X = E

X 是要计算的值,其他所有(A、B、C、D、E)都是数字.

X is the value to be computed, and all others (A,B,C,D,E) are all numbers.

例如:5 * (3 + 2*X) + 2*X = 39,计算时应该给X赋值2.

For example: 5 * (3 + 2*X) + 2*X = 39, on computing should assign X with the value 2.

将输入 Prolog 的查询(目标)将采用以下形式:

The query(goal) that would be entered into Prolog would take the form:

?- compute( 5*(3+2*X)+2*X = 39, Result).

结果"和X"的值应该绑定(分配)在一起.我如何编写 prolog 程序来做到这一点..?

The 'Result' and value of 'X' should be tied (assigned) together. How do I write the prolog program to do this..?

谢谢.

推荐答案

我假设您使用的是 fd,而不是 ic.它简化了一些事情.

I assume that you use fd, not ic. It simplifies things a bit.

:-lib(fd).

进一步假设你只有方程没有不等式,只有一个变量X,那么你可以分两步完成:

Further assuming that you only have equations and not inequalities, and only one variable X, then you can do it in two steps:

compute(L=R, X) :-
  term_variables(L, [X]),
  L #= R.

首先,从左侧提取变量,然后发布计算方程的约束.如果方程有效,这将实例化您的变量.

First, extract the variable from the left hand side, then post a constraint that computes the equation. If the equation is valid, this will instantiate your variable.

编辑

对于 ic 库,使用 eval(L)#=R.

这篇关于如何在prolog中进行算术表达式评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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