我是 Prolog 的新手。
我需要帮助编写一个谓词来查找和删除列表中的最小元素。
非常感谢!
最佳答案
如果所有列表项都是整数,我们可以使用clpfd !
:- use_module(library(clpfd)).
我们定义zmin_deleted/2
使用 maplist/2
, (#=<)/2
,
same_length/2
, 和 select/3
:
zmin_deleted(Zs1,Zs0) :-
same_length(Zs1,[_|Zs0]),
maplist(#=<(Min),Zs1),
select(Min,Zs1,Zs0).
示例查询:
?- zmin_deleted([3,2,7,8],Zs).
Zs = [3,7,8]
; false.
?- zmin_deleted([3,2,7,8,2],Zs).
Zs = [3, 7,8,2]
; Zs = [3,2,7,8 ]
; false.
请注意 zmin_deleted/2
也适用于“其他方向”:
?- zmin_deleted(Zs,[3,2,7,8]).
_A in inf..2, Zs = [_A, 3, 2, 7, 8]
; _A in inf..2, Zs = [ 3,_A, 2, 7, 8]
; _A in inf..2, Zs = [ 3, 2,_A, 7, 8]
; _A in inf..2, Zs = [ 3, 2, 7,_A, 8]
; _A in inf..2, Zs = [ 3, 2, 7, 8,_A]
; false.
关于Prolog:如何查找和删除最小列表元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339993/