I'm learning prolog, and this is the question I have a bit of a problem with right now
Write a Prolog function that takes two parameters: an input list, and an output variable that is the smallest one among the squares of each number in the input list
So far I've been able to make a squaring function
square([], []).
square([First | Rest], [FirstSquared | SquareRest]) :-
FirstSquared is First * First,
square(Rest, SquareRest).
But I don't know how to call this new list as a parameter that would look something like this when pseudo-called in SWI-Prolog
min(square[result_List], Answer).
Answer = *minimum number of list of squares*
Or is there an easier way to implement this in Prolog? If you could please explain the logic behind why you do things a certain way in Prolog, that'd be great since I'm more used to coding in C++ and C#. Thanks!
One of the main paradigms when working in Prolog is state transformation. Your square
(perhaps better named squared
) predicate transforms a list into a list of squares; what's left is to find the minimum element in that list:
min_square(L, M):-
squared(L, LS),
min_list(LS, M).
Writing your own min_list/2
should be straightforward. Just follow the same code skeleton that you used in the squared/2
predicate.
After you've mastered that, the next step in your code development is to fuse the two processing stages into one, as @CapelliC proposes in the comments, by adding one more argument to the squared
relation, the minimum-so-far.