Hunter
Hunter

Reputation: 65

Prolog - finding min element in list

I'm trying to find the minimum element in the list with comparing the squares. I did the following below:

min_elem([Min],Min).
min_elem([Head | Tail], Min) :-
   min_elem(Tail, Tail_min),
   Min is min(Head ^ 2, Tail_min ^ 2).

It actually worked with a few tests, but I noticed when tracing the following test:

Tracing example

So after it checks the square, it'll use the previous. I.e., when 8^2 goes to 64 and then it does 64^2. How can I prevent this? 🤔 Thanks!!!

Upvotes: 1

Views: 122

Answers (1)

If I understand you correctly, you want min_elem(XS,X) to be true iff X is the minimum of the squares in XS.

Based on this understanding, there are two problems:

  1. In your base case, you are not taking the square.

  2. In your recursive case, you are taking the square of the minimum of the squares in the tail.

To fix these problems, square the minimum in the base case and remove the square in the recursive case:

min_elem([X],Min) :- Min is X ^ 2.
min_elem([Head | Tail], Min) :-
   min_elem(Tail, Tail_min),
   Min is min(Head ^ 2, Tail_min).

Upvotes: 1

Related Questions