'if' in prolog?

前端 未结 10 1472
小鲜肉
小鲜肉 2020-12-03 02:12

Is there a way to do an if in prolog, e.g. if a variable is 0, then to do some actions (write text to the terminal). An else isn\'t even needed, but I can\'t find any docume

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 03:07

    Yes, there is such a control construct in ISO Prolog, called ->. You use it like this:

    ( condition -> then_clause ; else_clause )
    

    Here is an example that uses a chain of else-if-clauses:

    (   X < 0 ->
        writeln('X is negative.  That's weird!  Failing now.'),
        fail
    ;   X =:= 0 ->
        writeln('X is zero.')
    ;   writeln('X is positive.')
    )
    

    Note that if you omit the else-clause, the condition failing will mean that the whole if-statement will fail. Therefore, I recommend always including the else-clause (even if it is just true).

提交回复
热议问题