您可以使用predsort/3
這就像sort/2
,但通過調用您提供的比較謂詞來確定這些術語的順序。所以我們只需要編寫一個compare_values/3
謂詞來比較卡片的面值。我嘗試:
compare_values(D, card(A,_), card(B,_)) :-
nth0(X, [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king], A),
nth0(Y, [ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king], B),
compare(D, X, Y).
sort_cards(L, R) :-
predsort(compare_values, L, R).
的compare_values/3
謂詞的說明:
我們需要在下面的列表來定義排序:
[ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king]
怎麼樣?給定兩個值A
和B
,我們只需使用nth0/3
在列表中搜索A
和B
。 nth0/3
將給我們我們正在尋找的元素的位置。所以現在:
X = position of the element A in the ordered list
Y = position of the element B in the ordered list
但現在X
和Y
保證是數字!我們可以將它們與內置謂詞compare/3
進行比較。如果X < Y
卡A
出現在卡B
之前,反之亦然。
compare/3
將比較X
和Y
,並返回(>)
之一,(<)
,(=)
。
一個例子:
?- compare_values(D, card(ace, clubs), card(7, spades)).
nth0
有序值的列表中搜索ace
和7
。
- 現在
X = 0
和Y = 6
(的ace
和7
在列表中的索引)
compare(D, 0, 6)
統一與D = (<)
最後:在predsort/3
謂詞使用compare_values進行相應的分類列表中定義的順序by compare_values/3
查詢:
?- sort_cards([card(king, spades), card(ace,spades), card(3, clubs), card(7,diamonds), card(jack,clubs)], X).
X = [card(ace, spades), card(3, clubs), card(7, diamonds), card(jack, clubs), card(king, spades)].
你能解釋一下爲什麼你說這是錯誤的? – Lilz 2012-08-07 19:01:25
這是功課嗎?你有什麼嘗試? =) – Haile 2012-08-07 19:17:49
王牌和國王之間,哪一個更強? – 2012-08-08 22:33:26