Reputation: 3
I am new to prolog, and I think I have an really easy problem to solve, but i cant find sollution anywhere.
So i have a list of lists and I need to find all elements in it with esteblished length.
This is what i came to, but it is not working.
averegelist_([[]],[[]]).
averegelist_([Wo|List], Averege, NewL):-
length(Wo,N), N+1=:=Averege, averegelist_(List, NewL).
averegelist([Word|List1],Av, [Word|List2]):-
length(Word,N), N+1=\=Av, averegelist_(List1, Av, List2).
What i expected is somethig like this:
?- averegelist([['a','b','c'],['f','g'],['h','m']],2, X)).
X = ['f','g'].
X = ['h','m'].
False
Can somebody help me, please?
Edit:
So, I did it! For anyone interested in this topik this is what my code looks like:
split_on_delimiter(L, D, S) :-
split_on_delimiter_(L, D, R),
findall(X, (member(X, R), length(X,Length), Length > 0), S).
split_on_delimiter_([], _, [[]]).
split_on_delimiter_([D|T], D, [[]|T2]) :-
split_on_delimiter_(T, D, T2).
split_on_delimiter_([H|T], D, [[H|T2]|T3]) :-
dif(H, D),
split_on_delimiter_(T, D, [T2|T3]).
my_length([],0).
my_length([_|L],N) :- my_length(L,N1), N is N1 + 1.
my_length_lol([], 0).
my_length_lol([H|L],N) :- my_length(H,Add), my_length_lol(L,N1), N is N1 + Add.
countAver(L,Av):- length(L,ListN), my_length_lol(L,AllN), Av is div(AllN,ListN).
test_condition(X, Con):- length(X, N), N =:= Con.
select_element_on_condition([X|Xs], X, Con) :-
test_condition(X, Con).
select_element_on_condition([_|Xs], X, Con) :-
select_element_on_condition(Xs, X, Con).
findAvWord(L, X):- split_on_delimiter(L,' ', Words), countAver(Words, AvWordLength),
write(AvWordLength), select_element_on_condition(Words, X, AvWordLength).
findAvWord(L, X) L - is a list of simbols, X - is a word of averege Length in this list.
split_on_delimiter(L,D,S) S is - list of lists from L, based on delimiter(' ' in my case)
Upvotes: 0
Views: 366
Reputation: 60034
just to show how to solve such problem using modern libraries like apply and yall - where available -
averegelist(Lists, Length, ListsOfLength) :-
include({Length}/[List]>>length(List,Length), Lists, ListsOfLength).
Upvotes: 0
Reputation: 58294
I think you're making this problem harder than it really is. Here's a simple predicate framework that succeeds for list elements that meet a specific criteria. You should be able to adapt this to your problem.
select_element_on_condition([X|Xs], X) :-
test_condition(X).
select_element_on_condition([_|Xs], X) :-
select_element_on_condition(Xs, X).
In your case, your elements are lists, and the test condition is for the length.
Upvotes: 1