Prolog without if and else statements

后端 未结 4 761
南方客
南方客 2021-01-18 02:39

I am currently trying to learn some basic prolog. As I learn I want to stay away from if else statements to really understand the language. I am having trouble doing this th

4条回答
  •  梦毁少年i
    2021-01-18 03:17

    Your code has both syntactic and semantic issues.

    Predicates starts lower case, and the comma represent a conjunction. That is, you could read your clause as

    sample(A,B,C,What) if
        greaterthan(A,B,1.0) and lessthan(A,B,-1.0) and equal(A,B,C).
    

    then note that the What argument is useless, since it doesn't get a value - it's called a singleton.

    A possible way of writing disjunction (i.e. OR)

    sample(A,B,_,1) :- A > B.
    sample(A,B,C,C) :- A == B.
    sample(A,B,_,-1) :- A < B.
    

    Note the test A < B to guard the assignment of value -1. That's necessary because Prolog will execute all clause if required. The basic construct to force Prolog to avoid some computation we know should not be done it's the cut:

    sample(A,B,_,1) :- A > B, !.
    sample(A,B,C,C) :- A == B, !.
    sample(A,B,_,-1).
    

    Anyway, I think you should use the if/then/else syntax, even while learning.

    sample(A,B,C,W) :- A > B -> W = 1 ; A == B -> W = C ; W = -1.
    

提交回复
热议问题