Vicente Romão
Vicente Romão

Reputation: 5

Separate list from a list Prolog

I have this:

Lines=[['4'],['1','2','3','4'],['5','6','7','8'],['9', '10']]

And i want:

a=['4']
b=[['1','2','3','4']['5','6','7','8']]

To do this, I have to search for the elements inside of Lines that have length=a=['4'].

Can someone help me please?

Upvotes: 0

Views: 74

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74277

It's a simple one-liner:

select_sublists( [[L]|Xs] , Ys ) :-
  findall( X , (member(X,Xs), length(X,L)) , Ys ).

In the head of select_sublists/2, we ensure that the head of the passed-in list (the first argument) is a single element list containing the desired length. We extract that length, and use the tail as the list-of-lists to be searched.

The invocation of findall/3 in the body says:

  • find all X, such that
  • X is a member of Xs, and
  • the length of X is L,
  • returning the result list in Ys.

Running

Lines = [ [4] , [1,2,3,4] , [5,6,7,8] , [9, 10] ] ,
select_sublists( Lines, Filtered).

gives you the expected

Filtered = [ [1,2,3,4] , [5,6,7,8] ]

Upvotes: 1

brebs
brebs

Reputation: 4438

Can do with a "one-liner":

Lines=[[4],[1,2,3,4],[5,6,7,8],[9, 10]] ,
selectchk([Len], Lines, Lines0) ,
length(LineOfLen, Len) ,
findall(LineOfLen, member(LineOfLen, Lines0), LinesOfLen) .

Result in swi-prolog (ignoring the less-important variables):

Len = 4,
LinesOfLen = [[1,2,3,4],[5,6,7,8]].

Upvotes: 1

Related Questions