Prolog Question - How to create sublists of a certain length

I want to generate all the sublists of this list with the given property, that they have a certain length, referred to as an argument, and they also contain the element that contains the element, which is passed as a parameter. I managed to do this, but with the help of two predicates, and from the point of view of optimality - very slowly:

sublist([], []).
sublist([A|T], [A|L]):-
    sublist(T, L).
sublist(T, [_|L]):-
    sublist(T, L).

choose(T, L):-
    sublist(T, L),
    (dimension(2, T); dimension(1, T)),
    belongs(f, T).

Here I would like to return through the Tpredicate parameter of chooseall the subscriptions in the list L that are of size 2 or 1 and which contains an element f.
Predicates dimensionand memberhave the same meaning as predefined predicates length, respectively member.

Could you tell me how to include these two conditions in the sublistpredicate so that the program creates only those individual sublists?

+3
source share
1 answer

Subsequences of length are constructed below MinLen =< Len =< MaxLen. I do not know why you renamed lengthand member, therefore, I am going to use the originals. sublist/4calls yours sublist/2.

sublist(Sub,List,MinLen,MaxLen) :-
    between(MinLen,MaxLen,Len),
    length(Sub,Len),
    sublist(Sub,List).

, length , . choose/2

choose(Sub,List) :-
    sublist(Sub,List,1,2),
    member(f,Sub).

. , :

choose(Sub,List),
    (Sub = [f] ; Sub = [f,_] ; Sub = [_,f]),
    sublist(Sub,List).
+2

Source: https://habr.com/ru/post/1772995/


All Articles