Converting list to terms in Prolog - list

I have to implement the predicate cons(List, Term) that will take a list [Head|Tail] and convert it to terms, represented as next(Head, Tail). How do I do this? I don't even know where to start.
Here is the example of a successful query given in the question:
cons([a,b,c],X). /*query returns X=next(a,next(b,next(c,null))).*/

Doing most anything with lists will require that you consider two cases: the empty list and a list with a head and a sublist. Usually your base case is handling the empty list and your inductive case is handling the list with sublist.
First consider your base case:
cons([], null).
Now deal with your inductive case:
cons([X|Xs], next(X, Rest)) :- cons(Xs, Rest).

Related

Defining a list from scratch in prolog

So I need to define a list predicate: list(.) that returns true if the list is of the form cons(b,cons(d,cons(e,cons(h,nil)))). for the list bdeh.
I need to define the cons(.,.) binary predicate as well.
So far I have :
cons(atom(A),nil):- cons(A,nil).
cons(A,B):- cons(A, cons(B,_)).
list(atom(A)):-cons(A,nil).
list(A):- list(cons(_,A)).
but I don't think that the list(.) predicate is actually traversing through my cons. Can anyone help out in how to traverse the list or to proceed?
I need to define the cons(.,.) binary predicate as well.
Based on your question, cons/2 is not a predicate, it is a functor. A functor has no inherent semantical meaning. A functor is used to structure data in some way that makes sense to the programmer.
Your predicate list/1 needs to verify that the parameter is a list. Two things are lists:
the nil/0 constant; and
a compound term of the functor cons/2 where the second element is a list as well.
So we can define it like:
list(nil).
list(cons(_,X)) :-
list(X).
How does this work? The first clause simply states that nil is a list: if you call list(nil). it will succeed ("return" true). If you do not give it a nil, it will check the second clause and see if you gave it a compound term of cons/2. If that is not the case the clause (and thus the predicate call) will fail. If it is the case, it will unpack the compound term. Prolog is not interested in the first element (that's why we call it _), the second element we name X, and Prolog will perform a recursive call to list/1 with that second element to check if it is a list as well. Therefore it will traverse through the nested cons/2 structures until it finds a nil (or cut off earlier if the second element is not a nil and not a cons/2 compound term).

Prolog summing first indices of lists

I'm new to Prolog, trying to sum up only the first elements of each list.
takeFirst([[1,2,3],[4,5,6],[7,8,9]],R). --> R=1+4+7=12
It keeps outputting false and I don't understand what I'm missing here.
takeFirst([HF|_],[],HF):-!.
takeFirst([H|L1],R):- H=[_|_], L1=[_|_],!,takeFirst(H,L1,NN), R is NN.
takeFirst([HF|_],[K|L2],HF):- takeFirst(K,L2,NN), HF is HF+NN.
does anyone see what is wrong here?
Well your code is rather chaotic: you define a takeFirst/3 first (that probably should be the base case?). Next you define two recursive cases, but you somehow pass the head the list in the recursive call, etc.
Actually the problem is easy to solve. You first better redirect your takeFirst/2 to a takeFirst/3` with an accumulator:
takeFirst(L,R) :-
takeFirst(L,0,R).
Next we consider a base case: we reached the end of the list:
takeFirst([],R,R).
In this case we reached the end, and so the value of the accumulator, the variable we pass that keeps track of the sum thus far, is returned as the result.
In the recursive case, we are given a list [H|T] and we are interested in the head of the head HH so [[HH|_]|T]. In that case we add HH to the accumulator and do a recursive call with T:
takeFirst([[HH|_]|T],Ra,R) :-
Rb is Ra+HH,
takeFirst(T,Rb,R).
So putting it together we get:
takeFirst(L,R) :-
takeFirst(L,0,R).
takeFirst([],R,R).
takeFirst([[HH|_]|T],Ra,R) :-
Rb is Ra+HH,
takeFirst(T,Rb,R).
Something that was not very clear in your question is what should be done if there is an empty list in your list, like [[1,2,3],[],[7,8,9]]. The above predicate will fail: it expects that all lists have at least one element. In case you simply want to ignore these lists, you can alter your code into:
takeFirst2(L,R) :-
takeFirst2(L,0,R).
takeFirst2([],R,R).
takeFirst2([[]|T],Ra,R) :-
takeFirst2(T,Ra,R).
takeFirst2([[HH|_]|T],Ra,R) :-
Rb is Ra+HH,
takeFirst2(T,Rb,R).
So we add a case where the list follows the pattern [[]|T], in which case we simply perform a recursive call with the tail T.
Based on the given above predicates, constructing a list of heads is not hard as well:
heads([],[])
heads([[HH|_]|TA],[HH|TB]) :-
heads(TA,TB).

Prolog - Modifying and returning list

I want to define predicate which takes a list, adds an element to the list, let's say the number "1", and then returns the list.
I've found out I can add elements to a list using append/3, but I want to use in inside another predicate, thus why I want it to return "my modified list".
My object-oriented mindset tells me to ask the interpreter something like: ?-append(X,5,X). , so that it takes the list X, adds 5 to it, and returns "the new X", but I know that's not how unification works, so my mind is kinda in a glitch.
Can anyone please try to explain how something like this could be achievable?
You are already very close to the solution, so I only rephrase what you are beginning to sense already:
First, you cannot modify a list in pure Prolog.
Instead, you should think in terms of relations between entities. In your case, think in terms of relations between lists.
So, "adding the number 1" to a list is a relation between two lists, which could look like this:
list_with_one(Ls, [1|Ls]).
Note that this works in all directions! You can use it to:
generate answers
test particular cases
"reverse" the direction etc.
So, all you need to do in your case is to think in terms of relations between lists: One without an element, and how this relates to a different list with the element.
Obviously, these two lists will be indicated by different variables and different arguments.
Note in particular that append(X, 5, X) cannot hold: First of all, append/3 is meant to be a relation between lists, and 5 is not a list. Second, assuming you wrote for example append(Xs, [5], Xs), then this would be true if there where a list Xs such that if the element 5 were appended to Xs, the resulting list would again be Xs. Good luck finding such a list... Note also the naming convention to denote lists by letting the variable name end with an s.
It is also falls a bit short to blame this on your "object-oriented mindset", since you can have object oriented programming in Prolog too.
Although lists in Prolog cannot be modified, it is possible to add elements to the end of a list with an unspecified length. In this way, items can be "appended" to a list without creating another list:
:- initialization(main).
append_to_list(List,Item) :-
append_to_list(List,Item,0).
append_to_list(List,Item,Index) :-
% using SWI-Prolog's nth0 predicate
(nth0(Index,List,Check_Item),
var(Check_Item),
nth0(Index,List,Item));
(Next_Index is Index+1,
append_to_list(List,Item,Next_Index)).
main :-
A = [1,2,3|_],
append_to_list(A,4),
append_to_list(A,7),
writeln(A).
In this example, A becomes [1,2,3,4,7|_].

Prolog: List translation

I've been trying to figure out what list another list representation corresponds to:
[1|[2|[3|[4|[]]]]] is equivalent to the list [1,2,3,4] and [1,2,3,4|[]] etc.
But I just can't seem to figure out what list this corresponds to:
[[[[[]|1]|2]|3]|4]
If anyone can explain this for me I would be very grateful.
[H|T] is syntactic sugar for the real representation using the . functor: .(H,T) where H is the "head" (one list element), and T is the "tail" (which is itself a list in a standard list structure). So [1|[2|[3|[4|[]]]]] is .(1,.(2,.(3,.(4,[])))). Prolog also allows a non-list value for T, so [[[[[]|1]|2]|3]|4] is .(.(.(.([],1),2),3),4). The second structure doesn't really simplify any further than that from a list notational standpoint.
If you want to think in terms of "list" then [[[[[]|1]|2]|3]|4] is a list whose head is [[[[]|1]|2]|3] and tail is 4. And since 4 is not a list, the original list can be described as "improper" as #z5h indicated since the tail isn't a list (not even the empty list). Drilling down, the head [[[[]|1]|2]|3] is itself a list with head [[[]|1]|2] and tail 3. Another "improper" list. And so on. Therefore, the overall structure is an embedded list of lists, four levels deep, in which each list has a single head and a non-list tail (an "improper" list).
It's interesting to note that some of Prolog's predicates handle this type of list. For example:
append([], 1, L).
Will yield:
L = [[]|1]
You can then build your oddly formed list using append:
append([[]], 1, L1), % append 1 as the tail to [[]] giving L1
append([L1], 2, L2), % append 2 as the tail to [L1] giving L2
append([L2], 3, L3), % append 3 as the tail to [L2] giving L3
append([L3], 4, L4). % append 4 as the tail to [L3] giving L4
Which yields:
L4 = [[[[[]|1]|2]|3]|4]
Each append takes a list of one element (which is itself a list from the prior append, starting with [[]]) and appends a non-list tail to it.
It's called an "improper list".
Let me explain.
I think a few different ideas are at play here.
In general we know what a list is: it's an ordered collection.
How we represent a list literal in a programming language is another facet.
How the list is represented internally in the language, is another facet still.
What you have realized, is that there is a data structure you can represent in Prolog, with similar syntax to a list, but it somehow seems "improper". (It's not clear that you have asked much beyond "what is the meaning of this confusing thing?").
It turns out, that this structure is simply known as an "improper list". This data structure shows up often in languages that store lists internally as nested cons cells or similar. If you Google for that, you'll find plenty of resources for examples, usages, etc.

Using Prolog: Given a list check if the first element of the list equals the last element

Using prolog, I have to create a rule that determines, when given a list, if the first element of the list is equal to the last element of the list. Below is my thinking.
The Base Cases:
1) If The Parameter Is Not A List: Return False
2) If The Parameter Is A List But Empty: Return False
3) If The Parameter Is A List But Has One Element: Return False
The Recursive Step:
Recursively Going Through The List Getting The
First Element And TheLast Element Then Compare
fela() :- false. <-- Base Case One
fela([]):-false. <-- Base Case Two
fela([H]):-false. <-- Base Case Three
fela([H|T]):- H1 is H, H1 == T, fela(T,H1). <-- Recursive Step
Bellow Are Function For First, Last, Member
first(F, [F|_]).
last(L, [H|T]) :- last(L, T).
member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
I am having trouble with my recursive step, I am unsure of how to store the first element, and traverse the list and obtain the last element, then compare the results for a true/false answer. Could someone help me out
Thanks,
Erik :)
Here's an easy one:
fela(L) :- first(E, L), last(E, L).
Stare at that for a minute and let it really sink in.
Actually, it would be right, but your last/2 isn't, simply traversing the list with no base case that will ever succeed. A correct last/2 would look like this:
last(L, [L]).
last(E, [_|L]) :- last(E, L).
I see a lot of confused ideas in your case analysis. For one thing, in Prolog, you don't explicitly return true and false. You simply match what you match and the rest is failure. When dealing with lists, you automatically inherit the base case of the empty list and the inductive case of an element and the remainder of the list. This isn't sufficient to implement fela/1 from scratch because you have no way of remembering what your first element was. So if you want to build it from scratch you'll need a helper predicate so you can keep passing the first element along. It's going to look like this:
fela([H|T]) :- fela(H, T).
fela(First, [First]).
fela(First, [_|Xs]) :- fela(First, Xs).
Notice that we've preserved the analysis of one base case, one inductive case for handling the list. This is the usual situation when processing a recursive data structure. first/2 is a good example of when you don't follow the rule, because you aren't interested in one of the cases. Building the predicate out of first/2 and last/2 lets you escape the case analysis problem altogether, and is (in my opinion) more often what happens in practice.
Now I want to single out some of your ideas here for further comment. First, H1 is H is definitely not what you want. is/2 is exclusively for reducing arithmetic expressions. You will always have a variable on the left and an expression on the right, or it isn't meaningful. You're trying to do some kind of assignment here, but even H1 = H is not helpful here, because while Prolog has variables, it does not have assignables.
H1 is H, H1 == T says, implausibly, that H is both the head of the list and equivalent to the tail. This isn't ever really possible, because the tail is a list and the head is an element. Even if you could craft a situation where that were true, it definitely wouldn't be interesting to this predicate. Your recursive step here is really strange.
Another problem with your case analysis, case #3 should be true. With [X], X is both the first and the last element of the list, so fela/1 should be trivially true for all one-element lists.
I would advocate additional study. I think you have some odd notions that a little more reading might correct.