Probably a stupid question, but I can't find any documentation anywhere for it. 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 implementation of if.
相关问题
- Creating a SPARQL parameterized query using append
- How to join rules and print out outputs in prolog
- Splitting list and iterating in prolog
- Accumulating while in recursion/backtracking
- prolog trace how to use
相关文章
- What are the problems associated to Best First Sea
- How can I fix this circular predicate in Prolog?
- How to negate in Prolog
- Remove incorrect subsequent solutions without once
- prolog two lists are exactly the same
- Simplify Expressions in Prolog
- Check if any element's frequency is above a li
- Prolog — symetrical predicates
Prolog predicates 'unify' -
So, in an imperative langauge I'd write
In Prolog I'd write
which, when you understand both styles, is actually a lot clearer.
"I'm bazoo for the special case when foo is 5"
"I'm bazoo for the normal case when foo isn't 5"
Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found".
A, B
means "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e.X=3, write('X is 3'),nl
will print 'X is 3' when X=3, and will do nothing if X=2).A standard prolog predicate will do this.
will evaluate to true if you call it with 5 and fail(return false) if you run it with anything else. For not equal you use \=
Technically it is does not unify, but it is similar to not equal.
Learn Prolog Now is a good website for learning prolog.
Edit: To add another example.
There are essentially three different ways how to express something like if-then-else in Prolog. To compare them consider
char_class/2
. Fora
andb
the class should beab
andother
for all other terms. One could write this clumsily like so:To write things more compactly, an if-then-else construct is needed. Prolog has a built-in one:
While this answer is sound, it is incomplete. Just the first answer from
( Ch = a ; Ch = b )
is given. The other answers are chopped away. Not very relational, indeed.A better construct, often called a "soft cut" (don't believe the name, a cut is a cut is a cut), gives slightly better results (this is in YAP):
Alternatively, SICStus has
if/3
with very similar semantics:So the last answer is still suppressed. Now enter
library(reif)
for SICStus, YAP, and SWI. Install it and say:Note that all the
if_/3
is compiled away to a wildly nested if-then-else forwhich expands in YAP 6.3.4 to: