% 计算列表中原子的数目
count_atoms([], 0).
count_atoms([H|T], N) :-
atomic(H),
count_atoms(T, N1),
N is N1 + 1.
count_atoms([H|T], N) :-
not(atomic(H)),
count_atoms(T, N).
% 计算匹配的原子总数
match_atoms(_, [], 0).
match_atoms(A, [H|T], N) :-
A == H,
match_atoms(A, T, N1),
N is N1 + 1.
match_atoms(A, [H|T], N) :-
A \== H,
match_atoms(A, T, N).
% 计算列表中所有原子的数量
all_atoms_count([], 0).
all_atoms_count([H|T], N) :-
atomic(H),
all_atoms_count(T, N1),
N is N1 + 1.
all_atoms_count([H|T], N) :-
not(atomic(H)),
all_atoms_count(T, N).
% Write a predicate called rlen(X, N) to be true when N counts the total number of occurrences of atoms in the list X
rlen([], 0).
rlen([H|T], N) :-
% First calculate atomic count
all_atoms_count([H|T], N1),
% Then iterate through all atoms and match each one individually
rlen_helper([H|T], N1, N).
rlen_helper([], _, 0).
rlen_helper([H|T], M, N) :-
atomic(H),
match_atoms(H, [H|T], K),
M1 is M - K,
rlen_helper(T, M1, N1),
N is K + N1.
rlen_helper([H|T], M, N) :-
not(atomic(H)),
rlen_helper(T, M, N).
这里我们使用了三个辅助谓词来实现此问题。 总原子计数器(all_atoms_count),匹配原子计数器(