Search code examples
listprologprefix

Prefix in Prolog


I'm new in Prolog. I have a problem about predicate prefix but a little bit different.

I want to get a prefix of a list but until an element The list can have repeat elements.

An example:

prefix(Element, List, Prefix)
prefix(c, [a,b,c,d,e,f], [a, b])

The element is not included.

What I have so far is this

prefix(X, [X|T], []).
prefix(X, [Y|T], [Y|Z]):-
    prefix(X, T, Z).

But it does not work.

L = [a,b,c] ? prefix(b, L, Prefix).

no
?- 

Thanks


Solution

  • With dif/2 you can explicitly state that for any member X preceding Element, X \== Element:

    prefix(Element, [Element|_], []).
    prefix(Element, [Head|List], [Head|Prefix]) :-
        dif(Element, Head),
        prefix(Element, List, Prefix).
    

    or equally, because I wanted to use append/3 in the first iteration of my answer:

    prefix(Element, List, Prefix) :-
        append(Prefix, [Element|_Suffix], List),
        maplist(dif(Element), Prefix).
    

    For the suffix it is basically the same:

    suffix(Element, List, Suffix) :-
        append(_Prefix, [Element|Suffix], List),
        maplist(dif(Element), Suffix).
    

    If you don't want to use maplist(dif(Element), List):

    all_dif(_, []).
    all_dif(X, [H|T]) :- dif(X, H), all_dif(X, T).