1
votes

I would like to develop a function that evaluates a list and finds the minimum of it. I have done:

minimum([X],X).
minimum([X|Y],N) :- minimum(X,N), X < N.
minimum([X|Y],N) :- minimum(Y,N), X > N.

Buut it seems that the second and third rule are wrong because it says false.

I thought it was because of I was recursively calling with minimum(X,N) and it makes a mistake so I checked with:

minimum([X],X).
minimum([X|Y],N) :- minimum(X,X), X < N.
minimum([X|Y],N) :- minimum(Y,Y), X > N.

But it saays the same. Somebody could explain me how this behaves and give me a clue about where I could fix this! Thank you for your time.

3

3 Answers

2
votes

I have read this code which U understand better than MarioL proposed one:

min([X], X).
min([X,Y|Rest], Min) :-
   X =< Y,
   min([X|Rest], Min).
min([X,Y|Rest], Min) :-
   Y < X,
   min([Y|Rest], Min).
-1
votes

It looks like in your definition of minimum, the arguments are a list and an item.

When calling minimum in the second line

minimum([X|Y],N) :- minimum(X,X), X < N.

notice that in

minimum(X,X)

You're calling it with an item and an item instead of a list and an item. It's the same problem in third line. Hope that helps.

-1
votes

You have to use another variable in the definition of the predicate to be able to take its value, and then assign it according to the condition that is fulfilled (X < N1 or X > N1).

min([X],X).
min([X|Y],N):-min(Y,N1), X < N1, N is X.
min([X|Y],N):-min(Y,N1), X > N1, N is N1.