I am new to Prolog.
I need help writing a predicate which finds and deletes the minimum element in a list.
Thank you very much!
If all list items are integers, we can use clpfd!
:- use_module(library(clpfd)).
We define zmin_deleted/2 using maplist/2, (#=<)/2,
same_length/2, and select/3:
zmin_deleted(Zs1,Zs0) :-
same_length(Zs1,[_|Zs0]),
maplist(#=<(Min),Zs1),
select(Min,Zs1,Zs0).
Sample queries:
?- 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.
Note that zmin_deleted/2 also works in the "other direction":
?- 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.
Let me google it for you.
How could you find a minimum of a list..
Anyway, there is a nice min_list predicate.
?- min_list([1,2,2,3],X).
X = 1.
Here is a little example how could you remove some element from a list (notice, that all 2s is gone):
?- delete([1,2,2,3],2,X).
X = [1, 3].
If you wanna remove only first occasion of a element, use select:
?- select(2, [2,1,2,2,3], X), !.
X = [1, 2, 2, 3].
So your final answer could be something like that:
delete_min(A, C) :-
min_list(A, B),
select(B, A, C), !.
And
?- delete_min([1,1,2,3],X).
X = [1, 2, 3].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With