任何人都可以帮我编写一个函数来消除列表中每个子列表中的最大元素吗?我没有想法...... 到目前为止,我只知道如何编写delete子句:
delete(_,[],[]).
delete(E,[H|T],L):-
delete(E,T,L).
delete(E,[H|T],[H|T1):-
delete(E,T,T1).
列表[1,[2,4,3,4],5,[6,7]] ==> [1,[2,3],5,[6]]
答案 0 :(得分:1)
filter(_,[],[]).
filter(X,[X|T],L) :- filter(X,T,L).
filter(X,[H|T],L) :- X \= H, filter(X,T,C), append([H],C,L).
removemax([],[]).
removemax(X,Y) :- max_list(X,M), filter(M,X,Y).
deletemax([],[]).
deletemax([H|T],X) :- removemax(H,HH), deletemax(T,XX), append([HH],XX,X).
deletemax([H|T],X) :- \+ list(H), deletemax(T,XX), append([H],XX,X).
| ?- deletemax([1,[2,4,3,4],5,[6,7]],X).
X = [1,[2,3],5,[6]] ? ;
答案 1 :(得分:1)
这适用于任意嵌套的子列表。在这方面,它可能有点矫枉过正,但要求不明确。
% second list is the first list with sublists removed
remove_sublists([H|T], L) :-
( is_list(H)
-> L = T1
; L = [H|T1]
),
remove_sublists(T, T1).
remove_sublists([], []).
% max value in list ignoring sublists
% if L members are all lists, then this predicate fails
mymax(L, Max) :-
remove_sublists(L, F),
F \= [],
max_list(F, Max).
% delete maximum value from every sublist,
% and sublists of sublists
delete_max_subs([H|T], [H1|T1]) :-
( is_list(H)
-> ( mymax(H, M)
-> delete(H, M, HD)
; HD = H
),
delete_max_subs(HD, H1)
; H1 = H
),
delete_max_subs(T, T1).
delete_max_subs([], []).
一些结果:
| ?- delete_max_subs([1,[2,4,3,4],5,[6,7]], L).
L = [1,[2,3],5,[6]]
yes
| ?- delete_max_subs([[[1,2],2],[2,4,3,4],5,[6,7]], L).
L = [[[1]],[2,3],5,[6]]
yes
| ?- delete_max_subs([[[1,2,3],2,5],[2,4,3,4],5,[6,8,7]], L).
L = [[[1,2],2],[2,3],5,[6,7]]
yes
<小时/> 的附录强>
更多Visual / Turbo Prolog友好版本:
% second list is the first list with sublists removed
remove_sublists([H|T], T1) :-
list(H),
remove_sublists(T, T1).
remove_sublists([H|T], [H|T1]) :-
not(list(H)),
remove_sublists(T, T1).
remove_sublists([], []).
% max value in list ignoring sublists
mymax(L, Max) :-
remove_sublists(L, F),
F \= [],
max_list(F, Max). % I don't know if something like this exists in TP
% delete max recursively from L and all sublists
delete_max(L, R) :-
mymax(L, M),
delete(L, M, L1),
delete_max_subs(L1, R).
delete_max(L, R) :-
delete_max_subs(L, R).
delete_max([], []).
% delete maximum only from sublists
delete_max_subs([H|T], [H1|T1]) :-
list(H),
delete_max(H, H1),
delete_max_subs(T, T1).
delete_max_subs([H|T], [H|T1]) :-
not(list(H)),
delete_max_subs(T, T1).
delete_max_subs([], []).