从序言列表中返回多个值
在此Prolog练习中,我正在尝试从列表中返回数字n
的值。
例如:greate_than([5,6,1,7],5,x)
应返回x = 6; x = 7
。
我尝试通过执行此操作来解决此问题:
greater_than([],_,_). % to stop recursion when list is empty
greater_than([H|T],N,X) :-
H > N,
X is H,
greater_than(T,N,M). % if H>N return X=H
greater_than([H|T],N,X) :-
H =< N,
greater_than(T,N,X). % if H=<N just continue recursion.
我的代码在只有一个结果时起作用:oreal_than([1,2,5],2,x)
返回x = 5
。
但是它与多个结果无效:oreal_than([1,2,5,7],2,x)
返回false
。
我从中了解到,x
已经束缚到一个数字,并且(x为h)第二次返回false。
但是我不知道如何获得多个结果。
我试图更改变量名称:
greater_than([H|T],N,X) :-
H > N,
X is H,
greater_than(T,N,X1). % X1 for example
但是那没有用。
In this Prolog exercise, I'm trying to return the values from a list which are greater than a number N
.
For example: greater_than([5,6,1,7], 5, X)
should return X = 6 ; X = 7
.
I tried to solve this by doing:
greater_than([],_,_). % to stop recursion when list is empty
greater_than([H|T],N,X) :-
H > N,
X is H,
greater_than(T,N,M). % if H>N return X=H
greater_than([H|T],N,X) :-
H =< N,
greater_than(T,N,X). % if H=<N just continue recursion.
My code works when there is only one result: greater_than([1,2,5], 2, X)
returns X = 5
.
But it doesn't work with multiple results: greater_than([1,2,5,7], 2, X)
returns false
.
I understood from this that X
is already binded to a number and (X is H) for the second time returns false.
But I didn't know how to get multiple results.
I tried to change variables name:
greater_than([H|T],N,X) :-
H > N,
X is H,
greater_than(T,N,X1). % X1 for example
but that didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几乎是,但这并不是因为这些发生在不同的电话中,以便可以自己起作用。您的代码绑定x = 5,然后在下一个调用中它绑定了m = 7,您无处可见M的值。找到了所有答案,到达列表的结尾。
您正在将回溯与递归相结合,这是解决此问题的两种不同的方法。
回溯解决方案:
然后:
它找到一个答案,然后等待,然后您要求更多,然后找到更多。
递归解决方案在您的代码中列出了列表,而不是让Prolog做到这一点,例如,构建一个带有所有答案的列表:
然后:
Almost, but not quite because those happen in different calls so that could work on its own. Your code binds X=5 and then in the next call it binds M=7, and there's nowhere for you to see the value of M. The 7 is already used, when you search again, there's no more answers to find because it has found all the answers, reached the end of the list.
You are mixing up backtracking with recursion, two different ways of solving this.
A backtracking solution:
Then:
It finds one answer, and waits, then you ask for more, and it finds more.
A recursive solution walks the list in your code, instead of having Prolog do it, e.g. to build a list with all the answers:
Then: