一遍又一遍地给出相同的答案,而不是侦听器崩溃 - Prolog
警告,我对 Prolog 还很陌生。
我在 Prolog 中编写了一个分割谓词。它将一个列表拆分为两个新列表。一种包含大于 Key 的项目,另一种包含小于或等于 Key 的项目。它应该只返回一组答案。问题是如果我输入 ;为了检查更多答案,它不断地给我已经得到的答案,然后最终监听器崩溃。我想知道你能帮我解决这个问题吗?
代码:
split([],_,[],[]).
split([H|T],Key,Small,Big):-
H=<Key,
removeFirst(Small,H,NewSmall),
split(T,Key,NewSmall,Big).
split([H|T],Key,Small,Big):-
H>Key,
removeFirst(Big,H,NewBig),
split(T,Key,Small,NewBig).
removeFirst([H|T],H,T).
removeFirst(L,Key,Result):-
divide(L,Key,F,E),
X = F,
Y = E,
append(X,Y,Z),
Result = Z.
输出:
?- split([1,2,3,4,5],3,S,B).
S = [1, 2, 3]
B = [4, 5] ;
S = [1, 2, 3]
B = [4, 5] ;
S = [1, 2, 3]
B = [4, 5] ;
侦听器在第四次尝试时崩溃。
Warning, I'm quite new to Prolog.
I've written a split predicate in Prolog. It splits a list into two new lists. One that contains items greater than Key, and one that contains items less than or equal to Key. It should only ever return one set of answers. The problem is if I type ; to check for more answers, it keeps giving me the answer I already got and then eventually the listener crashes. I was wondering if you could help me fix this?
Code:
split([],_,[],[]).
split([H|T],Key,Small,Big):-
H=<Key,
removeFirst(Small,H,NewSmall),
split(T,Key,NewSmall,Big).
split([H|T],Key,Small,Big):-
H>Key,
removeFirst(Big,H,NewBig),
split(T,Key,Small,NewBig).
removeFirst([H|T],H,T).
removeFirst(L,Key,Result):-
divide(L,Key,F,E),
X = F,
Y = E,
append(X,Y,Z),
Result = Z.
Output:
?- split([1,2,3,4,5],3,S,B).
S = [1, 2, 3]
B = [4, 5] ;
S = [1, 2, 3]
B = [4, 5] ;
S = [1, 2, 3]
B = [4, 5] ;
Listener crashes on 4th attempt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您以另一种方式解决此算法:
它会是这样的:
I suggest you resolve this algorithm in another way:
It would be something like this: