Reputation: 95
I have some trouble when im trying to create a list with multiple sublists. I fail to see why my code is not working as expected.
solves(_, _, 0, _).
solves(Length, List, Stopcond, NList):- length(NL, Length),
append([NL], List, NList),
write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2).
?- solves(3, [], 3, B).
I want B to be a list with three sublists, each with three intern variables. When I write Nlist, it shows:
1. [[_G3207,_G3210,_G3213]]
2. [[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
3. [[_G3237,_G3240,_G3243],[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
4. B = [[_G3207, _G3210, _G3213]] .
But I don't understand why B becomes only the last element of the list. I want it to be the list on line 3. Can anyone see why and what i'm doing wrong? I'm pretty new to prolog.
Upvotes: 1
Views: 390
Reputation: 462
I think this is what you intended
solves(_, List, 0, List).
solves(Length, List, Stopcond, NList2):- length(NL, Length),
append([NL], List, NList),
%write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2).
What does your predicate try to do ( Ignoring the 3 element sublists for now )? It appends a list of length Stopcond to the 2nd argument passed (List).
How do you recursively construct a list of length TL Given a list of length L? You append a list of Length L with a list of Length 1 and try to construct a list of length TL-1 from our new list of length L+1. As a base case, You know that to construct a list of length TL from a list of length TL, you just need to return the list as is.
Your predicate returns a bigger-list consisting of Stopcond smaller-lists of length Length
each.
Recursively, A bigger-list of length Stopcond is a smaller-list of Length elements appended to a bigger-list of length Stopcond-1.
Base case: A bigger-list of size 0 is simply an empty list.
If we were just to consider 0's instead of the 3 element sublists,
solves(FinalList, 0, FinalList). % The result of appending a list of length 0 to the given list is the given list itself.
solves(List, StopCond, FinalList):- % Appends A list of length StopCond to List
Length1List = [0], % Create a list of length 1
append( Length1List, List, LengthPlus1List),
N is N-1,
solves( LengthPlus1List, N, FinalList).
Since you're new, It might help to write english comments against each line.
% Base case: stopping condition satisfied. List is the final List we need
solves(_, List, 0, List).
% Recursive case: We need to make one more list of length L and append/prepend it to List
solves(Length, List, Stopcond, NList2):-
length(NL, Length), % Create smaller-list of length Length
append([NL], List, NList), % Append it to the list we're building up
%write(NList), nl,
N is Stopcond-1,
solves(Length, NList, N, NList2). % Build Stopcond-1 more lists
Upvotes: 1