Prolog List Plateau

前端 未结 5 1705
执笔经年
执笔经年 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:20

    There are quite a lot of complicated answers here. Consider this one which doesn't use DCGs or many built-ins (perhaps simpler for a beginner):

    plateau([X|Xs], I, L) :-
        plateau(Xs, 1-1-X, I, L).
    
    plateau([X1|Xs], I0-L0-X0, I, L) :-
        X0 == X1, !,
        NL0 is L0 + 1,
        plateau(Xs, I0-NL0-X0, I, L).
    
    plateau(_, I-L-_, I, L) :-
        L > 1.
    
    plateau([X|Xs], I0-L0-_, I, L) :-
        NI is I0 + L0,
        plateau(Xs, NI-1-X, I, L).
    

    The first clause sets up the call which accumulates the (index)-(length)-(sublist element) tuple, as a term.

    The next clause increments the length if the next list element is the same (note the index isn't altered).

    The third clause is called only if the second clause failed when testing if the sublist element run was broken (because of the cut !), and returns a solution iff the length of the run was > 1.

    The last clause enables Prolog to backtrack and re-start the search from the last run.

    EDIT: gusbro's solution is actually very close to this one... +1.

提交回复
热议问题