Prolog - 将一些元素添加到同一个列表中 [英] Prolog - add some elements to same list

查看:69
本文介绍了Prolog - 将一些元素添加到同一个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Prolog 的列表中添加元素时遇到问题.我使用这个规则:

I have a problem to add elements in a list in Prolog. I use this rule:

add(X, L, [X|L]).

此规则在列表的头部添加一个元素.如果我将一些元素添加到同一个列表中,我会遇到这个问题:

This rule add an element in the Head of the list. If i would add some element to the same list i have this problem:

add(a, L, L1),
add(b, L1,L2),
add(c, L2,L3). 

L3= [a,b,c]

有没有一种方法可以在不改变变量名称的情况下在列表中添加元素... L1、L2、L3,但将它们添加到单个变量 L 中?

Is there a method to add elements in a list without change the name of variable... L1, L2, L3, but adding they to a single variable L?

推荐答案

这是由 DCG 隐式完成的,向非终结符添加(隐藏)差异列表参数.但是如果没有关于你的任务的更多细节,就很难暗示任何合理的用法.

That's implicitly done by DCG, adding (hidden) difference list arguments to non terminals. But without some more detail about your task it's hard to hint about any sensible usage.

SWI-Prolog 实际上有一些重要的功能,通过不可回溯的数据结构,执行具有副作用"的任务,通过解决方案链传播,但我不确定是否适合向您暗示此功能......

SWI-Prolog has actually some serious capability, via non backtrackable data structures, to perform tasks with 'side effects' propagating thru the solution chain, but I'm not sure if it's opportune to hint you about this feature...

编辑一个在故障驱动循环中更新 RBTree 的示例:

edit an example of updating an RBTree in a failure driven loop:

:- use_module(library(rbtrees)).
:- use_module(library(nb_rbtrees)).

 ordkey :- rb_empty(R),
   forall(member(W, [ls,mkdir,cd,ftp]),
     ( atom_length(W, K),
       (  nb_rb_get_node(R, K, N)
       -> nb_rb_node_value(N, Ws),
          nb_rb_set_node_value(N, [W|Ws])
       ;  nb_rb_insert(R, K, [W])
       )
    )), rb_visit(R, L), writeln(L).

yields

?- ordkey.
[2-[cd,ls],3-[ftp],5-[mkdir]]

这篇关于Prolog - 将一些元素添加到同一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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