简化 Prolog 中的表达式 [英] Simplify Expressions in Prolog

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

问题描述

我想问一下如何简化表达式,例如:

I wanted to ask how I can simplify expressions like:

1+2+a*5+0/b-c*0
= 3+a*5

特别是我如何在列表中分隔这些表达式.

And especially how can I separate such expressions in lists.

推荐答案

使用统一可以简化 Prolog 中的表达式,但这有时会导致意想不到的结果.在这个例子中,当匹配"一个表达式时,表达式中的两个不同变量是统一的.一种模式,即使它们的目的是不同的:

It's possible to simplify expressions in Prolog using unification, but this sometimes leads to unexpected results. In this example, two different variables in an expression are unified when "matching" a pattern, even if they were intended to be distinct:

:- initialization(main).

simplify(A+A,2*A).

main :-
    simplify(A+B,C),
    writeln(C). 

在这种情况下,simplify(A+B,C) 会将 AB 统一起来.

In this case, simplify(A+B,C) would unify A with B.

为了解决这个问题,我使用subsumes_term/2 匹配模式而不统一表达式中的变量.subsumes_term(A+A,Input) 将不匹配 A+B 除非 A 已经与 B 统一:

To solve this problem, I use subsumes_term/2 to match a pattern without unifying the variables in an expression. subsumes_term(A+A,Input) will not match A+B unless A is already unified with B:

simplify(Input,2*A) :-
    subsumes_term(A+A,Input).

这个 subsumes_term/2 谓词通常对元编程很有用:我用它写了一个 Prolog-to-Minizinc 编译器.

This subsumes_term/2 predicate is often useful for metaprogramming: I used it to write a Prolog-to-Minizinc compiler.

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

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