关于计数,首先尝试思考meaning的代码。
list_member_occ([], _, 0). % list is empty, 0 occurrences
list_member_occ([X|Xs], X, N) :- % list has the element at the head
list_member_occ(Xs, X, N0), % count number of elements in the tail
succ(N0, N). % the number of occurrences is the
% next natural number
list_member_occ([Y|Xs], X, N) :-
dif(X, Y), % head and the element are different
list_member_occ(Xs, X, N). % occurrences in the tail of the list
% is the total number
在这段代码中,succ(N0, N)
(可以说)是更好的说法“N
是后面的自然数N0
" than N is N0 + 1
。原因之一是succ/2 http://eu.swi-prolog.org/pldoc/doc_for?object=succ/2旨在用于各个方向:
?- succ(2, 3).
true.
?- succ(X, 4).
X = 3.
?- succ(1, X).
X = 2.
... 尽管is/2 http://eu.swi-prolog.org/pldoc/doc_for?object=%28is%29/2 should与未绑定的左操作数一起使用。接受这个查询
?- list_member_occ([1,1,2,1], X, 3).
...举个例子N
是一个数字而不是自由变量。
使用谓词:
?- list_member_occ([1,2,1], X, N).
X = 1,
N = 2 ;
X = 2,
N = 1 ;
N = 0,
dif(X, 1),
dif(X, 2),
dif(X, 1).
的一个有趣的属性dif/2 http://eu.swi-prolog.org/pldoc/doc_for?object=dif/2,相对于\=/2
,它对变量施加了约束X
在最后一个解决方案中:X
从现在开始,不能采用任何值1
, or 2
.
因为您使用以下方式获得所有答案的原因dif/2
, 考虑:
?- X = Y. % unify X and Y and succeed
X = Y.
?- X \= Y. % succeed if you cannot unify X and Y
false.
?- dif(X, Y). % succeed if X and Y are and will be different
dif(X, Y).
当你使用X \= Y
,Prolog 试图统一它的论点和如果统一成功则失败。这意味着您只能得到所有自由变量彼此统一的解决方案,但您会错过自由变量彼此不同的解决方案。
有关Y = ...
,当您在顶层进行查询时,它会向您报告在成功证明该查询期间进行的所有新变量绑定。作为最简单的例子:
3 和 5 之间的数字都包括哪些?
?- between(3, 5, X).
X = 3 ;
X = 4 ;
X = 5.
当然,您不需要打印出以下值X
用手;只需输入分号即可获得下一个答案。在最后一个答案之后,你会得到一个句号并返回到?-
prompt.
关于排序:它对整个列表进行排序,但仅shows你是排序列表的前 9 个元素。看此常见问题解答页面来自 SWI-Prolog http://eu.swi-prolog.org/FAQ/AllOutput.html。简而言之,最简单的就是输入; true
查询后,确保至少有一个选择点,然后使用w
and p
在显示整个术语和仅显示部分术语之间切换。
?- string_chars("the quick brown fox jumps over the lazy dog", Cs), sort(Cs, S) ; true.
Cs = [t, h, e, ' ', q, u, i, c, k|...],
S = [' ', a, b, c, d, e, f, g, h|...] [write]
Cs = [t, h, e, ' ', q, u, i, c, k, ' ', b, r, o, w, n, ' ', f, o, x, ' ', j, u, m, p, s, ' ', o, v, e, r, ' ', t, h, e, ' ', l, a, z, y, ' ', d, o, g],
S = [' ', a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] .
?- string_chars("the quick brown fox jumps over the lazy dog", Cs), sort(Cs, S) ; true.
Cs = [t, h, e, ' ', q, u, i, c, k, ' ', b, r, o, w, n, ' ', f, o, x, ' ', j, u, m, p, s, ' ', o, v, e, r, ' ', t, h, e, ' ', l, a, z, y, ' ', d, o, g],
S = [' ', a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] [print]
Cs = [t, h, e, ' ', q, u, i, c, k|...],
S = [' ', a, b, c, d, e, f, g, h|...] .
希望这可以帮助。