Prolog, having worked through several examples

I am working on some Prolog tutorials (nothing better to do, and I learned earlier this week, I really like programming, so I work on some paradigms) and got to the exercise asking me to write the delete_from_list / 3 predicate, which removes all the data in the list from list.

I solved it as follows:

delete_from_list([], _, []).
delete_from_list([Ah|At], X, [Ah|Bt]) :- Ah \= X, !, delete_from_list(At, X, Bt).
delete_from_list([_|Ct], X, Bt) :- delete_from_list(Ct, X, Bt).

What interests me is, and it may be more aesthetically pleasing than a practical purpose. How do you guys feel different? And why? This is mainly for a broader understanding of how to solve problems in the prolog :) For example, can this be done in rule 1?

+5
source share
3 answers

if-then-else ( ):

delete_from_list([], _, []).
delete_from_list([X|Xs], Y, Result) :-
    (X = Y ->
        Result = Result0
    ;
        Result = [X|Result0]
    ),
    delete_from_list(Xs, Y, Result0).

, - -, Result.

, , :

delete_from_list(Xs, Y, Result) :-
    (Xs = [] ->
        true
    ;
        Xs = [X|Xs0],
        delete_from_list(Xs0, Y, Result0),
        (X = Y ->
            Result = Result0
        ;
            Result = [X|Result0]
        )
    ).
+1

, /3

?- select(3,[1,2,3,4],X), !.
X = [1, 2, 4].
+1

Here is the removeAllFromList / 3 predicate using removeAllFromList / 4 with accumulator

removeAllFromList(List, X, ListAns) :-
    removeAllFromList(List, X, [], ListAnsReverse),
    reverse(ListAnsReverse, ListAns),!.

removeAllFromList([], _, ListAns, ListAns).
removeAllFromList([H | Tail], X, OutList, ListAns) :-
    (
    (H =\= X, append([H], OutList, OutListNew))
    ;(H = X, OutListNew = OutList)
    ),
    removeAllFromList(Tail, X, OutListNew, ListAns).
+1
source

All Articles