How Can I simulate a while loop in Prolog with unchangeable conditions?

前端 未结 4 1579
闹比i
闹比i 2021-01-02 20:49

So basically I am trying to simulate some C code in Prolog.

It is easy to simulate while loop in Prolog Here is the case:

C code:

int a = 1;
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 21:41

    Not very different from your prolog_while predicate:

    prolog_while(N, A) :-
        ( N==0 ->
             true
        ;
             N1 is N -1,
             A1 is A + 1,
             prolog_while(N1, A1)
        ).
    

    But most likely you want the final value of A be available to the caller of this predicate, so you have to return it via an additional argument:

    prolog_while(N, A, AFinal) :-
        ( N==0 ->
             AFinal = A
        ;
             N1 is N -1,
             A1 is A + 1,
             prolog_while(N1, A1, AFinal)
        ).
    

提交回复
热议问题