I’ve written the following recursive function to assign a parameter to the greater of two numbers:
max(A,B,X) :-
A >= B,
X is A.
max(A,B,X) :-
max(B,A,X).
This works as expected but as a newcomer to Prolog, I’m hesitant to believe this is the most efficient solution. Is there a better way of doing this?
Additionally, pressing ‘;’ after calling the function repeats it again. Is this correct behaviour?
Thank you in advance.
That seems convoluted to me. Try something like
Though you might want to put some type checking in.
[edited to remove the need for a cut, and provide better support for pre-instantiated 3rd parameter.]
Another option, of course, might be something like this:
This will throw an error is A or B is unbound, while the first example will work regardless of how it is invoked (so long as 2 arguments are instantiated). For instance, invoking it as
yields
X=5.