我試圖找到列表中最小元素的索引位置,並在對應索引位置處打印元素在另一個列表中。在列表中找到最小元素的索引並在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|_]).
,並中斷。
請告訴我我要出錯的地方。
謝謝你的答覆。 我得到'ERROR:=:=/2:參數沒有被充分實例化' B =:= H2-> A實際上做了什麼? =:=是數字相等,但什麼是 - >? – Bharat
這是一個if語句a - > b; c意味着如果a是真的,那麼b否則c。 mmmh可能需要使用模式匹配而不是B =:= H2 – bliss
哦,並且您需要編寫第二種情況,即在第二種情況後寫入的第二種情況。我認爲這就是爲什麼會出現錯誤。順序是:我的基例|你的第二個例子(謂詞)|我的第二個案例(謂詞)。因爲B在你的謂詞中被實例化 – bliss