prolog - 如果在列表中,Prolog如何在列表中添加元素
问题描述
我正在尝试用我自己的谓词做一个列表成员( member/2 )。
开始这个例子
?-app([a,r,t],[t,s,m,n,a],L3).
L3=[a,t]
我试着做类似的练习,所以我用 prolog 做了这个:
app([],_,[]).
app([H|T],[H1,T1],[H|L1]):- H is H1, L1 is H,! ,app(T,T1,L1).
app([_H|T],L,L2):- app(T,L,L2).
并且所有工作正常,但是列表中的值将在执行过程中被覆盖,实际上,跟踪是:
trace, app([3,2],[3,5],X).
Call: (9) app([3, 2], [3, 5], _7426) ? creep
Call: (10) 3 is 3 ? creep
Exit: (10) 3 is 3 ? creep
Call: (10) _7736 is 3 ? creep
Exit: (10) 3 is 3 ? creep
Call: (10) app([2], 5, 3) ? creep
Call: (11) app([], 5, 3) ? creep
Fail: (11) app([], 5, 3) ? creep
Fail: (10) app([2], 5, 3) ? creep
Fail: (9) app([3, 2], [3, 5], _7426) ? creep
false.
我试图以这种方式对基本情况进行修改:
app([],_,_N).
但输出完全错误:
trace, app([3,2],[3,5],X).
Call: (9) app([3, 2], [3, 5], _7426) ? creep
Call: (10) 3 is 3 ? creep
Exit: (10) 3 is 3 ? creep
Call: (10) _7736 is 3 ? creep
Exit: (10) 3 is 3 ? creep
Call: (10) app([2], 5, 3) ? creep
Call: (11) app([], 5, 3) ? creep
Exit: (11) app([], 5, 3) ? creep
Exit: (10) app([2], 5, 3) ? creep
Exit: (9) app([3, 2], [3, 5], [3|3]) ? creep
X = [3|3].
我错在哪里?
解决方案
我认为你正在尝试做一个sublist/2
谓词:
%! sublist(Sub, List)
% is true if Sub is a list that occurs in
% some position in List
sublist(Sub, List) :-
% first partition off some tail of the list
append(_Prefix, Tail, List),
% then get some prefix of the tail, this is a sublist
append(Sub, _TailTail, Tail).
有更多的方法可以做到这一点,但我认为append/3
很容易理解。这是一个与在列表中查找元素不同的问题member/2
,这里我们的问题是将列表分成块,因此实现与您在 中看到的非常不同member/2
。在 Prolog 中,您经常会发现解决方案的第一步是很好地定义问题。祝你在 Prolog 学习中好运。
推荐阅读
- apache-spark - EMR集群中如何限制spark job的最大内存消耗?
- hyperledger-fabric - 了解区块链(Hyperledger Fabric)概念
- javascript - 如何设置onclick验证javascript的条件
- entity-framework - ASP.NET Core Entity Framework 连接字符串超过 1 个登录用户
- python - pytorch中的坐标图像识别
- apache-spark - 将 Spark 作业远程提交到独立集群
- java - 在 Java 开发过程中如何正确绕过 reCAPTCHA
- python - 不知道为什么会这样?
- http - 如果客户端发送连接关闭标头,服务器是否可以与有效负载产生共鸣?
- python-3.x - 我需要创建一个 pyspark UDF,它通过比较从查询中输出一个表