I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.
For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:
goal(Stuff) :- do_something(X),
only_do_this_if_something(Y),
always_do_this(Z).
Currently, if only_do_this_if_something(Y)
fails, also always_do_this(Z)
doesnt happen as the whole goal turns false...
If I understand correctly, then what you need is a predicate like
include/3
:Usage example:
Now your homework becomes "how to implement
include/3
". Once you have implemented your version ofinclude/3
you can check if it matches SWI's version by looking at its source code:listing(include)
.you can use the if structure:
in this case:
or you simply write two clauses like:
try the ignore/1 predicate:
ignore/1 calls the only argument and succeeds whenever it fails or not:
Check the following programming pattern, which is used quite a lot in Prolog:
You have to either use the cut (!) to forbid backtracking or explicitly check that the condition do not apply in the latter clause.
Note that you said that you wanted to have an output list with the items for which 'something' applied (which is not what you wrote in your code)...
Applying this pattern to your problem it would look something like this: