Prolog: Increment value in list using nth1/3 - list

I am trying to implement a recursive Prolog predicate that when given a all 0 list ResultList with Dim elements and another list with values up to Dim, it runs trough this second list and increments +1 to the nth Element of ResultList and returns ResultList, so far I have:
increment_list([],_).
increment_list([Element|Tail],ResultList):-
nth1(Element,ResultList,_ is _+1),
increment_list(Tail,ResultList).
So for example
?-increment_list([1,2,4,3,4],[0,0,0,0]).
Would return:
[1,1,1,2]
What I'm apparently having difficulty and confusion is how to increment the value, is it possible to do it without defining an extra predicate or having a singleton Variable?

In prolog you cannot modify the value inside a list. You can do something like this:
increment_list([],L,L).
increment_list([H|T],LT,LO):-
increment_nth(H,1,LT,LT1),
increment_list(T,LT1,LO).
increment_nth(_,_,[],[]).
increment_nth(I,I,[H1|T1],[H2|T1]):-!,
succ(H1,H2).
increment_nth(I,C,[H|T1],[H|T2]):-
C1 is C+1,
increment_nth(I,C1,T1,T2).
Is basically a nested loop. In each loop you create a new list, which is the same previous list except the value at the index you consider which is the previous index incremented by one.
?- increment_list([1,2,4,3,4,1],[0,0,0,0],LO).
LO = [2, 1, 1, 2]
EDIT
Thanks to Daniel Lyons, i've modified the predicate.

Related

Iterate over a list and apply modulus/remainder to each element

A method that returns a new list formed by applying the second argument as a modulus operand on each list member, with two arguments: a list and a numerical value.
My current method only applies modulus operand to the first element and not all the elements.
I'm trying to use the cons operator to build the new list.
modList([Head | Tail], Num) -> [Head rem Num | Tail].
You're on the right track.
You're writing a recursive function, so what you need next are two things:
The recursive step: At some point in the body of your function, you need to apply your same function to the rest of the list (i.e. modList(Tail)).
The base case: If you apply the recursive step repeatedly, since you're removing one element from the list on each iteration, at some point, you'll have a list that doesn't match your function head pattern ([Head | Tail]). That will lead to a function_clause error that you can fix by… of course… adding a clause for that list. Since that clause will likely not need to be recursive (i.e. it will return a hardcoded value), that will close the recursion loop and your recursive function will be complete.
Extra tip: It's generally more idiomatic to use snake_case instead of camelCase for function names, module names, and atoms in general in Erlang. In other words, a more common name for your function would be mod_list/2.
You can do something like
> Num = 5.
5
> [X rem Y || X <- [1, 2, 3, 4, 5, 6, 7], Y <- [Num]].
[1,2,3,4,0,1,2]

Adding element to beginning of list, without creating a new list

I want to add [Startline, Assumption, assumption] to the beginning of list CheckedProof (without creating a new list).
Why doesn't this first code snippet give the same result for CheckedProof as the one where I just use append? Is it possible to yield the same result by just using append?
updateList([Element|List1], Element).
updateList(List1, Element):- !,
updateList([Element|List1], Element),!.
updateList(CheckedProof, [Startline, Assumption, assumption]).
append(CheckedProof, [], TemporaryCheckedProof)
append([[Startline, Assumption, assumption]], [TemporaryCheckedProof], CheckedProof).
A Prolog list is by definition a compound term with two arguments. The first argument is the first element of the list, and the second argument is the rest of the list.
Prolog provides the notation List = [H|T] where you have a list List that has a first element H and the rest of the list in T.
In other words, you don't have to do anything special to add an element at the front of an existing list. Here:
?- Old = [a,b,c], New = [hello|Old].
Old = [a, b, c],
New = [hello, a, b, c].
Not sure what you are doing in your updateList predicate but it seems unnecessary.

How does this ocaml recursive function work?

I'm pretty new to ocaml and I'm having a hard time with this func
I know what it does but not HOW! With a given list, it returns the minimum value of the list and the rest of the list as a pair.
sepmin [2;1;3;4] == (1,[2;3;4])
val sepmin : 'a list -> 'a * 'a list
# let rec sepmin = function
[h] -> h, []
|h::t -> let h1, t1 = sepmin t in
min h h1, (max h h1)::t1;;
Could you guys help me out with the recursive part t.t
First, it is applied to the list's tail recursively. Say, it returns h1 and t1 that are the minimum of the tail and all the other elements of the tail. Next, this element, h, is compared against h1. If it is less than h1, then the pair (h, h1::t1) returned; otherwise the pair (h1, h::t1) is returned. Since the function is called recursively, then probably one of these pairs is returned to the previous recursion point (and its first element is again compared against that point's list head). As far as I can see, the function does not care much about the original order of the elements, i.e. for the list [1; 4; 2; 5; 6] it should return (1, [2; 4; 5; 6]), 2 and 4 are reordered in the result.
A good way to think about recursion is to take it in two pieces. First, what does the function do when the input is trivial? Second (this is the tricky part), assuming the function works for small inputs, how does it transform a bigger intput into a smaller one and use the answer for the smaller case to calculate the correct result for the bigger case.
The trivial case for this function is a list of one element. The answer is obvious in that case.
For a longer list, you can use your recursive power to get the correct answer for the tail of the list (which is a shorter list, hence the recursion will work by assumption). Once you know the answer for the tail of the list, you can construct the correct answer for the full list: the max of the head of the list and the answer for the tail is the overall maximum. You need to add the smaller of these two values back to the list.

Return head of list recursively prolog

I want to return the first element of the list each time the user requests for another value i.e. List = [1, 2, 3], when the program is executed it returns 1, however, when ; is pressed (user asks for another value) then 2 is returned and so on, till the list is empty.
Though I have managed to list all values at once, but the key question here is that, how can I wait and let the user decide of he wants another value or not.
Just do this:
member( X, List ).
This will enumerate the next member of List on each ;. Each call to the predicate will instantiate the next member of List in X until all of the members are exhausted.
yes there is a built-in function that does that, but I think you should try to write it yourself to better understand Prolog.
each_one([A|_],A).
one of the elements of a list is its head element.
each_one([_|B],X):- each_one(B,X).
more elements are in the list's tail. This is the recursive clause.
There are no elements in the empty list, so we don't write anything (though we could write each_one([],_):- fail. with the same effect).
Now you can try it:
4 ?- each_one([1,2,3],X).
X = 1
Prolog shows you the first solution and waits for your response. You press ';' to continue:
;
X = 2 ;
X = 3 ;
false.

Prolog length of a list

How can I calculate the length of a list
?- size_sub([[b,a,g], [9,3,7,4], [6]], X).
X = [3, 4, 1].
?- size_sub([[c,g,e,w], [7]], X).
X = [4, 1].
?- size_sub([], X).
X = [].
Ok you need to start with the base case which is the last answer
so size_sub([],X). is true if X=[] so first you write that as a rule.
size_sub([],[]).
Then you need to do the inductive step a list that is one longer than the previous. I am going to assume that you have a size/2 function for determining the size of a single list (if not please comment).
So the inductive step is going to operate on the length of the first parameter so N->N+1. We would represent this by striping off the head of the list syntax will be [H|T] now the second parameter (your answer) is going to be the length of H with the result of calling size_sub on T. As we cannot specify rules in the parameters in the header we will use N to represent the length of H and T2 to represent the result of size_sub on T.
So the first part of the rule becomes size_sub([H|T],[N|T2]):-
now we follow it with the predicates that will assert the values for N and T2.
size(H,N),
size_sub(T,T2).
putting that all together you get
size_sub([],[]).
size_sub([H|T],[N|T2]):-
size(H,N),
size_sub(T,T2).
size/2 is a far simpler case and following the same process of base + inductive you should be able to create the rules for it. Please comment if you need further help.
** EDIT - Request for size/2 definition **
To define size/2
Start with the base case, the empty list has a size of 0.
size([],0).
Now the inductive step. The size of list of length(N+1) is the size of a list of length(N). So lets define our list as [_|T] I've defined the list using _ to represent the head because we never use it so we can just use the anonymous variable. Lets use N to represent the length of T, and M to be N+1.
so
size([_|T],M):-
now lets define N
size(T,N),
and finally assert that M is equal to N + 1
M is N+1.
so putting everything together
size([],0).
size([_|T],N):-
size(T,M),
N is M+1.
size_sub([],[]).
size_sub([H|T],[N|T2]):-
size(H,N),
size_sub(T,T2).
To map length/2 over a list of lists, we can use the meta-predicate maplist/3 like this:
size_sub(Xss,Ls):-
maplist(length,Xss,Ls).