1

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.

Yone
  • 2,064
  • 5
  • 25
  • 56

3 Answers3

2

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).
false
  • 10,264
  • 13
  • 101
  • 209
Yone
  • 2,064
  • 5
  • 25
  • 56
-1

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.

pellucidcoder
  • 127
  • 3
  • 9
-1

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.
Mario L
  • 224
  • 1
  • 11
  • 1
    Fails for `min([1,1],X).` apart from being [extremely inefficient](http://stackoverflow.com/a/19941560/772868). – false May 05 '17 at 22:53
  • Thank you MarioL it looks like I needed and for my assignment it was stated that the source list had no repeated elements so we don't have the [1,1] fail problem; although I would like to know why it fails there! – Yone May 06 '17 at 17:19
  • I would fail because I did not define a predicate where X1 and N1 are equal (only defined for cases where X N1), greetings. – Mario L May 07 '17 at 16:15