Prolog List Plateau

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

    You could do something like this:

    plateau([Item|Tail], I, Len):-
      plateau(Tail, 1, Item, 1, I, Len).
    
    plateau(List, From, NItem, Len, From, Len):-
      (List=[Item|_] -> (Item\=NItem;var(Item)); List = []),
      Len > 1.
    plateau([Item|Tail], IFrom, Item, ILen, From, Len):-
      MLen is ILen + 1,
      plateau(Tail, IFrom, Item, MLen, From, Len).
    plateau([Item|Tail], IFrom, OItem, ILen, From, Len):-
      OItem \= Item,
      NFrom is IFrom + ILen,
      plateau(Tail, NFrom, Item, 1, From, Len).
    

    The first clause of plateau/6 deals with the termination of the sublist. It is either the case that the item is different from the one you are looking or you reached the end of the list. In that case we only proceed if the current length is greater than one.

    The second clause deals with the recursion step for the case the we are still matching the element in the list. It just adds one to the counter of current sublist and does the recursion.

    The last clause deals with the case of a new (different) item found in the list and just resets the counters and does recursion.

提交回复
热议问题