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

2019-02-27 15:22发布

问题:

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(' : '),read(M1),
        N is N2+1, X is N1-1, loop(N,X).

guys i new at prolog there i have loop input, how to add from loop input (M1) to list, then find Max and Min on the list? my data is integer.

回答1:

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.



标签: prolog