【问题标题】:PROLOG-number of positive and negative numbersPROLOG-正负数个数
【发布时间】:2014-08-20 02:40:25
【问题描述】:

我收到了以下必须在 PROLOG 中解决的任务。我们有正数和负数以及变量PN 的列表。变量P 必须在列表中包含多个正数,变量N 必须包含多个负数。如果列表中的所有数字都是正数,我制作的部分效果很好,但是它会崩溃。有人可以帮助我吗?谢谢

   numbers([],0,0).
   numbers([G|R],P,N):-
      numbers(R,NR,NN),
      P is NR+1,
      G>0.
   numbers([G|R],P,N):-
      numbers(R,NR,NN),
      N is NN+1,
      G<0.
   numbers([],P,N).

【问题讨论】:

    标签: prolog


    【解决方案1】:

    首先,基本情况:当列表为空时,没有数字

    numbers([], 0, 0).
    

    现在,对于一般情况

    numbers([H|T], X, Y) :-
        % you compute the rest of the list
        numbers(T, X1, Y1),
        % you increment the correct number
        (H > 0
        -> X is X1 + 1, Y1 = Y
        ;  H < 0
        ->  X = X1, Y is Y1+1
        ;   X = X1, Y1 = Y).
    

    编辑我修正了 0 的情况

    【讨论】:

      【解决方案2】:

      试试这样的。一个常见的 Prolog 习惯用法是使用辅助谓词累加器

      count_by_sign( Xs , P , N ) :- count_by_sign( Xs , 0 , 0 , P , N ) .
      
      count_by_sign( [] , P , N , P, N ) .
      count_by_sign( [X|Xs] , A , B , P , N ) :-
        tick(X,A,B,A1,B1) ,
        count_by_sign(Xs,A1,B1,P,N)
        .
      
      tick( X , P , N , P  , N1 ) :- % negative numbers
        X < 0 ,
        N1 is N+1
        .
      tick( X , P , N , P1 , N  ) :- % positive numbers
        X > 0 ,
        P1 is P+1
        .
      tick( X , P , N , P  , N  ) :- % zero is unsigned
        X = 0
        .
      

      【讨论】:

        【解决方案3】:

        这里是如何使用库(aggregate):

        numbers(L,P,N) :-
          aggregate(t(sum(P),sum(N)),
            X^(member(X,L), (X > 0 -> P=1,N=0 ; X < 0 -> P=0,N=1)), t(P,N)).
        

        测试:

        ?- numbers([3,-1,4,0,-4,1],P,N).
        P = 3,
        N = 2.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-31
          • 1970-01-01
          • 2013-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多