Prolog program returns false

前端 未结 3 1458
温柔的废话
温柔的废话 2021-01-29 04:34

I implemented the following power program in Prolog:

puissance(_,0,1).
puissance(X,N,P) :- N>0,A is N-1, puissance(X,A,Z), P is Z*X.

The cod

3条回答
  •  孤城傲影
    2021-01-29 05:13

    Can do like this instead:

    puissance(X,N,P) :-
      ( N > 0 ->
        A is N-1,
        puissance(X,A,Z),
        P is Z*X
      ; P = 1 ).
    

    Then it will just print one answer.

    (Your code leaves a `choice point' at every recursive call, because you have two disjuncts and no cut. Using if-then-else or a cut somewhere removes those. Then it depends on the interpreter what happens. Sicstus still asks if you want ((to try to find)) more answers.)

提交回复
热议问题