'How to chain multiple IF statements in logic programming?
I want to update my knowledge base after receiving a new state,
not((hasBeenVisited(X-1, Y)); not(wall(X-1, Y)) -> asserta(isDangerous(X-1, Y));
not(((hasBeenVisited(X+1, Y)); not(wall(X+1, Y)) -> asserta(isDangerous(X+1, Y));
not((hasBeenVisited(X, Y-1)); not(wall(X, Y-1)) -> asserta(isDangerous(X, Y-1));
not((hasBeenVisited(X, Y+1)); not(wall(X, Y+1)) -> asserta(isDangerous(X, Y+1));
problem with my code is that if the first line evaluates to true, then, the next lines are not evaluated, because of the logical OR ";".
If I were to change the ";" to logical AND ",", then if one of the conditions fail, the entire predicate returns false instead of true.
How do I chain multiple IFs statements? In procedural programming, we can do something like this:
if condition1 then statements1;
if condition2 then statements2;
if condition3 then statement3;
...
Should I even do that with prolog because I am still thinking in terms of procedural programming...
Solution 1:[1]
Your imperative example:
if condition1 then statements1;
if condition2 then statements2;
if condition3 then statements3;
becomes this shape:
(condition1 -> statements1 ; true),
(condition2 -> statements2 ; true),
(condition3 -> statements3 ; true).
with "code blocks" wrapped in () parens and making sure there is always a true whether the condition holds or not, so the block is true AND the next block can run.
You're right that coding in this way with imperative rules and state updates is fighting against the design of Prolog, and not leaning on its strengths. Also X+1 doesn't work the way you are using it, and I wonder if you are thinking that isDangerous(X+1, Y) will return a value like it was a function call and that return goes into asserta(<here>)? If so, that won't happen either.
Probably what you are being pushed towards is building a list of movements to get through a maze, and should be leaning on Prolog's backtracking to find the walls and dangerous places, step back from them and go another way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TessellatingHeckler |
