Conditional Statements in Prolog

前端 未结 1 1878
自闭症患者
自闭症患者 2020-12-21 07:52

I have just started prolog and was wondering if we can implement conditional statements like(if.else)in Prolog also and if so how?? Can someone implement this code in Prolog

相关标签:
1条回答
  • 2020-12-21 08:47

    One way to do it:

    test(A) :-
        (   A =:= 2 ->
            write('A is 2')
        ;   A =:= 3 ->
            write('A is 3')
        ;   write('HAhahahahaah')
        ).
    

    Another way to do it:

    test(2) :-
        write('A is 2').
    test(3) :-
        write('A is 3').
    test(A) :-
        A \= 2, A \= 3,
        write('HAhahahahaah').
    

    There are differences with these two codes, like choice points, behavior when A is not instantiated, and if A is treated as a number or not. But both will work the same way (except choice points left) and as expected with queries test(2)., test(3)., test(42).

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