查找列表中最小元素的索引&在Prolog中获取另一个列表中相应索引位置的元素
我试图找到列表中最小元素的索引位置,并在另一个列表中的相应索引位置打印该元素。
例如:
?- min2(X,Y,[a,b,c],[5,3,7]).
X= b
y= 3
代码:
min2(A,B,[A|_],[B|_]).
min2(A,B,[X|T1],[Y|T2]) :- smallest(W,[Y|T2]), % using a predicate to find the min element in the list
B is W, % setting B to the result of above(i.e the min element)
min2(A,B,T1,T2). % looking up position corresponding to min element in list1
在列表中查找最小元素的谓词是:
smallest(Head, [Head]).
smallest(Element, [Head|Tail]) :- smallest(E, Tail), Head =< E, Element is Head.
smallest(Element, [Head|Tail]) :- smallest(E, Tail), E < Head , Element is E.
我得到的结果是:
X = a,
Y = 5 ;
X = b,
Y = 3 ;
false.
它也以某种方式选择第一个元素。我的基本情况可能是错误的?我尝试将基本情况更改为 min2(A,B,[A|_],[B|_]).
但它崩溃了。
请告诉我哪里出错了。
I am trying to find the index position of the minimum element in a list and print the element at the corresponding index position in another list.
For example:
?- min2(X,Y,[a,b,c],[5,3,7]).
X= b
y= 3
Code:
min2(A,B,[A|_],[B|_]).
min2(A,B,[X|T1],[Y|T2]) :- smallest(W,[Y|T2]), % using a predicate to find the min element in the list
B is W, % setting B to the result of above(i.e the min element)
min2(A,B,T1,T2). % looking up position corresponding to min element in list1
the predicate for finding the min element in the list is:
smallest(Head, [Head]).
smallest(Element, [Head|Tail]) :- smallest(E, Tail), Head =< E, Element is Head.
smallest(Element, [Head|Tail]) :- smallest(E, Tail), E < Head , Element is E.
The result I am getting is :
X = a,
Y = 5 ;
X = b,
Y = 3 ;
false.
It somehow picks the first element also. My base case could be wrong? I tried altering the base case to min2(A,B,[A|_],[B|_]).
and it breaks.
Please show me where I am going wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您首先编写了事实
(A,B,[A|_],[B|_]).
,因此它首先返回 2 个列表的头元素。您需要修剪列表的头部,直到第二个列表的头部等于 B。一旦发现 list2 的头部等于 B,就需要返回 list1 的头部。
也许你想尝试这个:
无法尝试(因为我目前在工作)。但我认为应该是这样的。
Since you first write the fact
(A,B,[A|_],[B|_]).
it first returns the head elements of the 2 list.You need to trim the heads of the lists until the head of the second list is equal to B. As soon as you find that the head of list2 is equal to B, you need to return the head of list1.
Maybe you want to try this:
Couldn't try it (because im currently at work). But i think it should be smth like this.
为了给你更多的东西,我对最小的定义以相反的顺序,比如 min_list:
我认为更简单(你的也是复制的,而不是你自己的代码)。相应的谓词是,就像我在 DaniWeb 上发布的那样:
通过将这些结合到不言而喻的最小规则中,您将得到 min2 谓词。我的意思是你让事情变得过于复杂
To give you little thing more, my definition of smallest in opposite order, like min_list:
Simpler I think (and yours was also copy, not your own code). The corresponding predicate was, like I posted in DaniWeb:
By combining these in self-obvious minimal rule, you get your min2 predicate. I mean that you are way overcomplicating things