Prolog 对卡片列表进行排序序言

Prolog 对卡片列表进行排序序言,prolog,bubble-sort,Prolog,Bubble Sort,我有一个卡片结构列表,例如: [card(ace, spades), card(10, diamonds), card(king, clubs)] 有人能帮我理解如何根据面值来分类吗 我有这个: bubblesort(L, L1) :- ( bubble(L, L2) -> bubblesort(L2, L1) ; L = L1 ). bubble([card(A,A2), card(B,B2)|T], L) :-

我有一个卡片结构列表,例如:

[card(ace, spades), card(10, diamonds), card(king, clubs)]
有人能帮我理解如何根据面值来分类吗

我有这个:

bubblesort(L, L1) :-
        (   bubble(L, L2)
        ->  bubblesort(L2, L1)
        ;   L = L1 ).

bubble([card(A,A2), card(B,B2)|T], L) :-
        (   A > B
        ->  L = [card(B,B2), card(A,A2)|T]
        ;   L = [card(A,A2) | L1],
            bubble([card(B,B2)|T], L1)).
除非你有
牌(ace,spades)
或类似的东西,因为
ace
不是一个你可以使用的数字

它类似于
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).

比较值/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
肯定是数字!我们可以将它们与内置谓词进行比较。如果
X
A
在卡
B
之前,反之亦然

compare/3
将比较
X
Y
,并返回
(>)
(您可以使用

它类似于
sort/2
,但通过调用您输入的比较谓词来确定术语的顺序。因此,我们只需要编写一个
compare\u 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).

比较值/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
保证是数字!我们可以将它们与内置谓词进行比较。如果
X
A
在卡
B
之前,反之亦然


compare/3
将比较
X
Y
,并返回
(>)
(你能解释一下你为什么说它错了吗?这是作业吗?你尝试了什么?=)在王牌和王牌之间,哪一个更强?你能解释一下为什么你说这是错误的吗?这是作业吗?你试过什么吗?=)在王牌和王牌之间,哪一个更强?+1表示感叹号。:)但是在王牌和王牌之间,哪一个排名更高?@Lilz,好吧,把它放在名单的末尾。我刚才举了一个例子,您可以定义您喜欢的任何顺序。+1表示感叹号。:)但是在王牌和王牌之间,哪一个排名更高?@Lilz,好吧,把它放在名单的末尾。我只是举了个例子,你可以定义你喜欢的任何顺序。