Prolog, find minimum in a list

前端 未结 13 1925
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 01:25

in short: How to find min value in a list? (thanks for the advise kaarel)

long story:

I have created a weighted graph in amzi prolog and given 2 nodes, I am

相关标签:
13条回答
  • 2020-12-07 01:41

    This looks right to me (from here).

    min_in_list([Min],Min).                 % We've found the minimum
    
    min_in_list([H,K|T],M) :-
        H =< K,                             % H is less than or equal to K
        min_in_list([H|T],M).               % so use H
    
    min_in_list([H,K|T],M) :-
        H > K,                              % H is greater than K
        min_in_list([K|T],M).               % so use K
    
    0 讨论(0)
  • 2020-12-07 01:41

    This program may be slow, but I like to write obviously correct code when I can.

    smallest(List,Min) :- sort(List,[Min|_]).

    0 讨论(0)
  • 2020-12-07 01:42
    %Usage: minl(List, Minimum).
    minl([Only], Only).
    minl([Head|Tail], Minimum) :-
        minl(Tail, TailMin),
        Minimum is min(Head, TailMin). 
    

    The second rule does the recursion, in english "get the smallest value in the tail, and set Minimum to the smaller of that and the head". The first rule is the base case, "the minimum value of a list of one, is the only value in the list".

    Test:

    | ?- minl([2,4,1],1).
    
    true ? 
    
    yes
    | ?- minl([2,4,1],X).
    
    X = 1 ? 
    
    yes
    

    You can use it to check a value in the first case, or you can have prolog compute the value in the second case.

    0 讨论(0)
  • 2020-12-07 01:42

    % find minimum in a list

    min([Y],Y):-!.
    
    min([H|L],H):-min(L,Z),H=<Z.
    
    min([H|L],Z):-min(L,Z),H>=Z.
    

    % so whattaya think!

    0 讨论(0)
  • 2020-12-07 01:46

    This works and seems reasonably efficient.

    min_in_list([M],M).    
    min_in_list([H|T],X) :-
        min_in_list(T,M),
        (H < M, X = H; X = M).   
    
    min_list(X,Y) :- min_in_list(X,Y), !.
    
    0 讨论(0)
  • 2020-12-07 01:47

    Similar to andersoj, but using a cut instead of double comparison:

    min([X], X).
    
    min([X, Y | R], Min) :-
        X < Y, !,
        min([X | R], Min).
    
    min([X, Y | R], Min) :-
       min([Y | R], Min).
    
    0 讨论(0)
提交回复
热议问题