Prolog, find minimum in a list

前端 未结 13 1960
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题