序言:效率 [英] Prolog: efficiency

查看:74
本文介绍了序言:效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序言中有没有办法缩短以下内容:

Is there a way in prolog to make the following shorter:

rule(prop, [1/2,2/2]).
rule(prop, [1/3,2/3,3/3]).
rule(prop, [1/4,2/4,3/4,4/4]).
rule(prop, [1/5,2/5,3/5,4/5,5/5]).
rule(prop, [1/6,2/6,3/6,4/6,5/6,6/6]).
rule(prop, [1/7,2/7,3/7,4/7,5/7,6/7,7/7]).

推荐答案

对于 6 种不同规则的情况,以下代码不一定更短",但它更具可扩展性,这可能是您真正的意思.

The following code isn't necessarily "shorter" for the case of 6 different rules, but it is more scalable, which is probably what you really mean.

您可以将其分解如下.首先,生成一个列表的规则:

You can break this down as follows. First, a rule that generates one list:

list_props(N, N, [N/N]).
list_props(X, N, [X/N|T]) :-
    X >= 1,
    X < N,
    X1 is X + 1,
    list_props(X1, N, T).

当你调用它时,它会生成一个从第一个参数到最后一个参数的比例列表,最后一个参数是分母.例如:

When you call this, it generates one list of proportions from the first argument to the last with the last argument being the denominator. For example:

| ?- list_props(1, 4, L).

L = [1/4,2/4,3/4,4/4] ? a

| ?-

请注意,您可以使用 integer(N) 和条件强制 N 为整数 >= 1,但我很简短,并没有这样做以上.

Note that you could enforce that N be an integer >= 1 using integer(N) and conditions, but I was being brief and didn't do that in the above.

您可以在顶级谓词中使用它:

You can use this in your top level predicate:

rule(prop, L) :-
    between(2, 7, X),
    list_props(1, X, L).

产生的结果:

| ?- rule(prop, L).

L = [1/2,2/2] ? ;

L = [1/3,2/3,3/3] ? ;

L = [1/4,2/4,3/4,4/4] ? ;

L = [1/5,2/5,3/5,4/5,5/5] ? ;

L = [1/6,2/6,3/6,4/6,5/6,6/6] ? ;

L = [1/7,2/7,3/7,4/7,5/7,6/7,7/7] ? ;

(2 ms) no
| ?-

这篇关于序言:效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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