Skip to content

Instantly share code, notes, and snippets.

@oxling
Created August 11, 2012 21:30
Show Gist options
  • Save oxling/3327426 to your computer and use it in GitHub Desktop.
Save oxling/3327426 to your computer and use it in GitHub Desktop.
Finding the minimum in a list in Prolog
% This version doesn't work.
min_wrong([Item], Item).
min_wrong([Item | List], Item) :-
min_wrong(List, List_Answer),
Item =< List_Answer.
min_wrong([_Item | List], Answer) :-
min_wrong(List, Answer).
% Output:
%
% [debug] ?- min_wrong([1,2,3], Answer).
% Answer = 1 ;
% Answer = 1 ;
% Answer = 2 ;
% Answer = 3 ;
% false.
% This version does work
min([Item], Item).
min([Item | List], Item) :-
min(List, List_Answer),
Item =< List_Answer, !.
min([_Item | List], Answer) :-
min(List, Answer).
% Here's the built-in function
min_list([H|T], Min) :-
min_list(T, H, Min).
min_list([], Min, Min).
min_list([H|T], Min0, Min) :-
Min1 is min(H, Min0),
min_list(T, Min1, Min).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment