I am trying to find the minimum value of a list (as a learning experience, so without min
).
My approach is the following:
minimo([X], X).
minimo([X,Y|Tail], N):-
(X > Y, minimo([Y,Tail], Y));
(X <= Y, minimo([X,Tail], X)).
This gives me the following error:
Syntax error: Operator expected
So my questions are:
Thanks in advance.
There are several bugs in your program:
as pointed out by Joe Lehmann, there is no '<='/2
. It must be '=<'/2
.
when you call minimo/2
recursively, you construct the lists wrong. Instead of [Y,Tail]
use [Y|Tail]
. Otherwise, you get a list with a list as second element.
you bind the second argument of the recursive call of minimo/2
to Y
or X
. Instead it must be bound to N
. Otherwise, your N
will never be instantiated.
You can improve your program further by adding cuts or using if-then-else ('->'
+ ;
):
minimo([X], X) :- !.
minimo([X,Y|Tail], N):-
( X > Y ->
minimo([Y|Tail], N)
;
minimo([X|Tail], N)
).