Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: How to find and remove minimum list element?

Tags:

prolog

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!

like image 912
user1913592 Avatar asked Dec 06 '25 06:12

user1913592


2 Answers

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.
like image 157
repeat Avatar answered Dec 08 '25 01:12

repeat


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].
like image 31
ДМИТРИЙ МАЛИКОВ Avatar answered Dec 08 '25 01:12

ДМИТРИЙ МАЛИКОВ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!