简化 Prolog 中的表达式

编程入门 行业动态 更新时间:2024-10-28 01:20:07
本文介绍了简化 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) 会将 A 与 B 统一起来.

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 中的表达式

本文发布于:2023-06-05 01:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/508985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!