简体   繁体   中英

SWI-Prolog, first delete an element then reverse the resulting list

I currently have my head wrapped around this issue - its driving me crazy. I'm new to Prolog, so I'm still understanding the very basics. From the title, all I'm trying to do is delete an element from a list, and then from that resulting list, reverse it.

So far, I done a bit of research in how do these functions separately on different lists, but I don't know exactly how to perform both of them (delete then reverse) on a single list..

My reverse and delete are below:

reverse(List, RevList) :-
    reverselist(List, [], RevList).
reverselist([], RevList, RevList).
reverselist([E|Elements], Accu, RevList) :-
    reverselist(Elements, [E|Accu], RevList).

del(Element, [Element|Tail], Tail).
del(Element, [Y|Tail], [Y|Tail1]) :-
    del(Element, Tail, Tail1).

And my attempt:

delete_reverse(Element, [Element|Tail], Tail1) :-
    // no idea what im doing below..
    del(Element, Tail, Tail1),
    reverse(Tail1, Tail).

First, your del is missing a base case:

del(_,[],[]).

Then, your delete_reverse is almost right: you should use a different variable name to unify the results of del and the input of reverse :

delete_reverse(Element, [Element|Tail], Tail1) :-
    del(Element, Tail, Temp),
    reverse_family(Temp, Tail1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM