Prolog List Plateau

前端 未结 5 1704
执笔经年
执笔经年 2020-12-21 05:14

Just got introduced to prolog, trying to get through some simple exercises, but I\'ve been getting kind of stuck on this one. I\'m trying to write a program that outputs all

5条回答
  •  青春惊慌失措
    2020-12-21 05:18

    I tried using nth1/3 builtin, but had more trouble to get it working... anyway, here another implementation:

    plateau(L, I, Len) :-
        plateau(L, 1, I, Len).
    plateau(L, P, I, Len) :-
        nth1(P, L, E),
        skipseq(P, L, E, J),
        (   J > P,
            Len is J - P + 1,
            I is P
        ;   Q is J + 1,
            plateau(L, Q, I, Len)
        ).
    
    % get the index J of last element E (after I)
    skipseq(I, L, E, J) :-
        T is I + 1,
        nth1(T, L, E),
        !, skipseq(T, L, E, J).
    skipseq(I, _, _, I).
    

    test:

    [debug]  ?- plateau([a,x,x,x,u,u,h,w],I,N).
    I = 2,
    N = 3 ;
    I = 5,
    N = 2 ;
    false.
    

提交回复
热议问题