Prolog separating into two lists issue

后端 未结 4 1273
太阳男子
太阳男子 2020-12-12 06:40

I have a prolog assignment.

I need to look at the first item in a list, see if its following items are the same until they are not and separate the lists by the firs

4条回答
  •  无人及你
    2020-12-12 07:26

    grab(Xs, Ys, Zs) :-
       eqprefix(Xs, Ys, Zs).
    
    eqprefix([],[],[]).
    eqprefix([X],[],[X]).
    eqprefix([X,Y|Xs], [], [X,Y|Xs]) :-
        dif(X,Y).
    eqprefix([X,X|Xs], [X|Ys], Zs) :-
       eqprefix2([X|Xs], Ys, Zs).
    
    eqprefix2([X], [X], []).
    eqprefix2([X,Y|Xs], [X], [Y|Xs]) :-
        dif(X,Y).
    eqprefix2([X,X|Xs], [X|Ys], Zs) :-
        eqprefix2([X|Xs], Ys, Zs).
    
    ?- eqprefix([a,a,a,b,c],Ys,Zs).
    Ys = [a, a, a],
    Zs = [b, c] ;
    false.
    
    ?- eqprefix(Xs,[a,a,a],[b,c]).
    Xs = [a, a, a, b, c] ;
    false.
    
    ?- eqprefix([A,B,C,D,E],[a|Ys],[b,c]).
    A = B, B = C, C = a,
    D = b,
    E = c,
    Ys = [a, a] ;
    false.
    

    In the definition you gave, you get many different answers:

    ?- grab([a,a,a,b,c],Ys,Zs).
      Ys = [a, a], Zs = [a, b, c]
    ; Ys = [a],    Zs = [a, a, b, c]
    ; Ys = [a],    Zs = [a, a, b, c]
    ; Ys = [],     Zs = [a, a, a, b, c].
    

提交回复
热议问题