Reputation: 123
The question requires us to code Prolog that if there is no element in the list L that is less than A, is satisfied when M is A; otherwise it is satisfied when M is the minimum of the list L
minLessThan([],A,A).
minLessThan([H|T], A, M) :-
H >= A,
M is A,
minLessThan(T, A, M).
minLessThan([H|T], A, M) :-
H < A,
M is H,
minLessThan(T, A, M).
Now that, my result valids for the first part of the sentence, however it keeps returns me false when the M is the minimum of the list L, i assume that the problem occurs when the list L is empty, which it returns the A, any way to solve this?
Upvotes: 3
Views: 1248
Reputation: 123
minLessThan([],A,A).
minLessThan([H|T], A, M) :-
H >= A,
minLessThan(T, A, M).
minLessThan([H|T], A, M) :-
H < A,
minLessThan(T, H, M).
Here is my edited answer, works fine for now .
Upvotes: 0
Reputation: 22585
As this is homework I am only going to give you some advice:
For what you are trying to do, you should not instantiate M in the second and third clause until the recursive step.
That is, you don't have to put the M is A
and M is H
because M will get instantiated in the base case (the first clause).
Also, the recursive call in the third clause should use H
instead of A
as the second argument, because you have found an item less than the current minimum.
Note that the second parameter of minLessThan
can be read as "the current minimum found", so you should call the procedure giving some initial value, otherwise instantiation errors will occur.
Upvotes: 2