Add input to list then sum,find Max and Min on the list

后端 未结 1 959
一向
一向 2021-01-25 03:15
menu:- write(\'how much data to input  : \'),read(N1),
   N2 is 0,loop(N2,N1).


loop(N2,N1):-N1>0, N3 is N2+1,
        write(\'Input data \'),write(N3),write(\' : \'         


        
相关标签:
1条回答
  • 2021-01-25 03:49

    If you just start Prolog from command line you get this:

    ?- 
    

    And then the cursor is waiting for you to input things. You can then write a list of integers between brackets and put it in a variable and it looks like this:

    ?- [1,2,3] = X.
    

    Now if you want to see if all elements are integer you can write:

    ?- [1,2,3] = X,
       maplist(integer, X).
    

    Now if you want to find min and max you can use library predicates like this:

    ?- [1,2,3] = X,
       maplist(integer, X),
       min_list(X, Min),
       max_list(X, Max),
       sum_list(X, Sum).
    

    If you really want to do all at once you can do like this maybe:

    integers_min_max_sum([I|Is], Min, Max, Sum) :-
        integers_min_max_sum_1(Is, I, I, I, Min, Max, Sum).
    
    integers_min_max_1([], Min, Max, Sum, Min, Max, Sum).
    integers_min_max_1([I|Is], Min0, Max0, Sum0, Min, Max, Sum) :-
        integer(I),
        Min1 is min(Min0, I),
        Max1 is max(Max0, I),
        Sum1 is Sum0 + I,
        integers_min_max_1(Is, Min1, Max1, Sum1, Min, Max, Sum).
    
    ?- integers_min_max_sum([1,2,3, ...], Min, Max, Sum).
    

    But really is this any better than using library predicates? Maybe, or maybe not.

    0 讨论(0)
提交回复
热议问题