Check out the following programming pattern that Prolog uses quite a lot:
- Iterate through the list, one item at a time
- Set base case for recursion
- In one sentence, check if any conditions apply and do something, then continue recursing
- In the next section, skip the element and continue recursing
You need to either use the cut (!) To prohibit backtracking, or explicitly verify that the condition does not apply in the last section.
Please note that you said that you want to have an output list with elements for which "something" is applied (this is not what you wrote in the code) ...
Applying this template to your problem will look something like this:
myRecursion([], []). % This is the base case myRecursion([Item|Tail], [Item|NTail]):- something_applies(...), do_something(...), only_do_this_if_something(...), always_do_this(...). myRecursion(Tail, NTail). myRecursion([Item|Tail], NTail):- not(something_applies(...)), do_something(...), always_do_this(...), myRecursion(Tail, NTail).
source share