I need to build a new list with a “loop”. Basically i can’t use recursion explicitly, so i am using append to go through lists of list.
I can get the element. Problem is i need to check this element and if something is true it returns another element i need to put back into the list. It does check correctly and it changes correctly.
Problem i am having is how do i create a completely new list.
So, if i had
[[1,1,1],[2,6,2],[3,3,3]]
I go through each element. say i get to the 6 and it changes. So i need to create a new list like so,
[[1,1,1],[2,10,2],[3,3,3]].
Right now my main problem is just creating each row. If i can create each row, i will be able to create a list of lists.
So to break this down a little more, lets just worry about [1,1,1].
I go through each element while appending the new element to a newlist. the new list is now [1,1,1]
I have this:
set(Row,Col,Bin,TheEntry,Bout) :-
append(ListLeft, [R|_], Bin),
append(ListLeft2, [C|_], R),
length(ListLeft, LenR),
length(ListLeft2,LenC),
CurrRow is LenR + 1,
CurrCol is LenC + 1,
getChar(C, Row, Col, CurrRow, CurrCol,TheEntry, NewC),
appendhere?.
I need to create a new list there with the character returned from NewC. Not sure how to do this.
Any clues?
Thanks.
To give you an idea about how to use
append/3to extract an item from a list of lists, consider the following predicate calledreplace/2:This non-recursive predicate takes, as
Input, a list of lists, and backtracks to find an elementEwithin an inner listLthat can be replaced viareplaceElement/2; if so, it is replaced by constructing the inner list first (NewL), then uses this new list in the construction of the new outer list (Out), as the result.Note that this simply serves to demonstrate how to use
append/3to break apart a list of lists to retrieve individual elements as you need via backtracking, and not recursion, as requested. Once an elementEis found to be replaceable byNewEviareplaceElement/3, it is used in the construction of the list again usingappend/3as shown.Also note that this suggestion (which is intended to help you, not be your final answer) also happens to replace only a single element within an inner list, if any at all. If you want to do multiple replacements of the input list in a single call to
replace/2or similar using this technique, then you will almost certainly need a recursive definition, or the ability to use the global database viaassert. I’m happy to be corrected if someone else can provide a definition as a counterexample.With this example predicate
replace/2, together with, say, the following fact:Executing the following gives us your required behaviour:
If you cannot use cut (
!), it is fine to omit it, but note that the second clausereplace(In, In)will cause all calls toreplace/2to backtrack at least once to give you the input list back. If this behaviour is undesirable, omitting this second clause will causereplace/2to fail outright if there is no replacement to be made.