单边统一可以改进错误处理吗? [英] Can single sided unification improve error handling?

查看:39
本文介绍了单边统一可以改进错误处理吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

受到这个问题的启发,我正在努力解决错误
处理反向/2.所以我尝试了这个实现:

Inspired by this question, I am trying to harden error
handling of reverse/2. So I tried this implementation:

reverse(X, Y) :- reverse(X, [], Y).

reverse(X, _, _) :- var(X), throw(error(instantiation_error,_)).
reverse([], X, R) :- !, R = X.
reverse([X|Y], Z, R) :- !, reverse(Y, [X|Z], R).
reverse(X, _, _) :- throw(error(type_error(list,X),_)).

一切正常,直到我尝试将 reverse/2 作为生成器:

Everything works fine, until I try reverse/2 as a generator:

?- reverse([1,2,3],X).
X = [3, 2, 1].

?- reverse(2,X).
ERROR: Type error: `list' expected, found `2' (an integer)

?- reverse(X,Y).
ERROR: Arguments are not sufficiently instantiated

单边统一是否可以改变这种情况,一些基于单边统一的典型解决方案,使得生成器 reverse(X,Y) 仍然可以工作?SWI-Prolog 8.3.19 提供了单边统一.

Can single sided unification change the situation, some typical solution based on single sided unification so that the generator reverse(X,Y) would still work? Single sided unification is available in SWI-Prolog 8.3.19.

推荐答案

恐怕我无法提出单方面的统一解决方案.相反, (\=)/2 形式的正常统一可能很有用.我几乎不使用 (\=)/2 .该解决方案的灵感来自 Dijkstra 守卫 if-fi,链接到本文末尾的论文:

I am afraid I cannot present a single sided unification solution. Its rather that normal unification in the form of (\=)/2 could be useful. I hardly use (\=)/2 ever. The solution is inspired by Dijkstra guards if-fi, link to paper at end of this post:

if
Cond1 -> ActionList1
..
Condn -> ActionList2
fi

如果条件 Cond1,..,Condn 都不满足,则 if-fi 中止.所以我们只需使用条件否定的连词:

The if-fi aborts if none of the conditions Cond1,..,Condn is satisfied. So we simply use a conjunction of the negation of the conditions:

reverse(X, Y) :- reverse(X, [], Y).

reverse(X, _, _) :- X \= [], X \= [_|_], throw(error(type_error(list,X),_)).
reverse([], X, R) :- R = X.
reverse([X|Y], Z, R) :- reverse(Y, [X|Z], R). 

似乎有效:

?- reverse([1,2,3],X).
X = [3, 2, 1].

?- reverse(2,X).
ERROR: Type error: `list' expected, found `2' (an integer)

?- reverse(X,Y).
X = Y, Y = [] ;
X = Y, Y = [_1778] ;
X = [_1778, _2648],
Y = [_2648, _1778] ;
Etc..

所以单边统一可能是错误的方法?我不知道.上述解决方案会产生开销,除非某些索引可能会优化掉 (\=)/2.甚至可以与属性变量一起工作.

So single sided unification might be the wrong approach? I dont know. The above solution incures an overhead, unless some indexing might optimize away (\=)/2. Could even work in connection with attributed variables.

程序的不确定性和形式推导
Edsger W. Dijkstra - Burroughs Corporation
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.90.97&rep=rep1&type=pdf

这篇关于单边统一可以改进错误处理吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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