Prolog takeout function - error in solution

Disclaimer: Dieser Thread wurde aus dem alten Forum importiert. Daher werden eventuell nicht alle Formatierungen richtig angezeigt. Der ursprüngliche Thread beginnt im zweiten Post dieses Threads.

Prolog takeout function - error in solution
Just wanted to point out a very small error maybe this helps somebody understand Prolog better:

“Start with a helper predicate takeout(X,LSA,LSB) that is true iff LSB is the result
of removing the first occurence of X from LSA.”

Given solution:

takeout(X,[X|T],T).
takeout(X,[H|T1],[H|T2]) :- takeout(X,T1,T2).

Correction:

takeout(X,[X|T],T).
takeout(X,[H|T1],[H|T2]) :- X=H, takeout(X,T1,T2).

Try both with “takeout(1, [1,2,3,1], X).” and don’t forget to click on next.

Alternative (EDIT: in this context false, see comment below!) correction would be the following code; it’s often easier to write stuff down like this, especially when doing a search:

takeout(X,[X|T],T):-!.
takeout(X,[H|T1],[H|T2]) :- takeout(X,T1,T2).

The ! tells Prolog to stop all backtracking after its occurrence. Because Prolog goes from top to bottom it is correct to stop when we found X because we have our one and only solution.

The problem with this soultion however is, that it also stops the permutations from backtracking and you therefore only get 1 result

1 Like