自定义Prolog算术函数 [英] Custom Prolog arithmetic function

查看:295
本文介绍了自定义Prolog算术函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似内置算术运算符的东西,这些东西在Prolog中(特别是在SWI-Prolog中)具有返回值.例如.如果运行A is (1+2) + (3+2).,它将返回A = 8..

I'm looking for something like built-in arithmetic operators that has a return value in Prolog (specifically in SWI-Prolog). E.g. if you run A is (1+2) + (3+2)., it returns A = 8..

如何定义func运算符以执行类似+运算符的操作?
例如. A is (2 func 3) func (4 func (2+1))..

How can I define func operator to do something like + operator?
E.g. A is (2 func 3) func (4 func (2+1))..

推荐答案

为了像+运算符(以及许多其他运算符)一样将函数func内联放置,您需要定义一个优先顺序func及其参数.您可以使用 op/3 在SWI-PROLOG中实现此目标.

In order to situate your function func inline just as the + operator (along with many others), you'll need to define a precedence order for func and it's arguments. You can achieve this in SWI-PROLOG with op/3.

例如,伪指令(使用func/2的前面的代码):

For example, the directive (preceding code where func/2 is used):

:- op(500,yfx,func).

要实现func/2,您可以为您的语言编写一个元解释器(即,您编写一个PROLOG程序,该程序可以解析包含func的术语表达式并根据需要对其进行解释),或者如果func/2为严格来说,您可以将 arithmetic_function/1 用作指令,如下所示:

To implement func/2, you can either write a meta-interpreter for your language (i.e., you write a PROLOG program which parses term expressions including func and interprets them as you wish), or if func/2 is strictly arithmetic, you can use arithmetic_function/1 also as a directive, as follows:

:- arithmetic_function(func/2).

使用以下func/2定义进行测试:

Testing this with the following definition for func/2:

func(X, Y, Z) :- 
    Z is X + Y.

举个例子,

?- A is (2 func 3) func (4 func (2+1)).
A = 12.

这篇关于自定义Prolog算术函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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