Prolog: Checking lengths of lists inside a list - list

I'm totally new in Prolog and I have problems handling a list that contains other lists.
I have some lists like this:
[([5],23),([1],23),([2],43),([4],29),([3],14),([5,1,4,3],47)]
and I am trying to take the (sub)list with the biggest length and put it first at the list
in this example I want the result to be like this:
([5,1,4,3],47),([5],23),([1],23),([2],43),([4],29),([3],14)]
(don't care whether it will be removed or not from it's starting place).
Thanks to all who will try to help

Presuming that you want to use the built-in sort routine (I'm using SWI-Prolog as example here), then the following would work:
calcLen((List,K),(N,List,K)):- length(List,N).
delLen((_,List,K),(List,K)).
sortlen(List,Sorted):-
maplist(calcLen,List,List1),
sort(0,#>=,List1, List2),
maplist(delLen,List2,Sorted).
The two predicates calcLen and delLen insert and remove a length calculation at the front of the pairs in the list -- making them triples. The maplist predicate applies calcLen (and later delLen) to a list.

Related

How to create a function that returns a list that is a union of the elements of a nested list in Ocaml?

If I was given a set of lists within a list in Ocaml, for example [[3;1;3]; [4]; [1;2;3]], then how can we implement a function to return a list that is a union of the values of the nested list (so the output from the example will return [1;2;3;4])? I tried removing duplicates from the list, but it didn't work as intended. I am also restricted to using the List module only.
Restricted to using the List module only? Sounds like homework with an arbitrary limit like that. so I don't want to give a fully working solution. However, if you look through the List documentation, you'll see a couple of functions that can be combined to do what you want.
concat, which takes a list of lists and flattens them out into a single list, and sort_uniq, which sorts a list and removes duplicates.
So you just have to take your list of lists, turn it into a single list, and sort_uniq that (With an appropriate comparison function) to get your desired results.

Prolog - how to generate list of specific length?

I'm doing this exercise for which I have to write a predicate randomnames/1 for generating a random list of three names (no duplicates allowed). I have a database with 10 names in it already and they all correspond to a number, for example: name(1, Mary).
I wrote a predicate for generating one random name:
randomname(Name) :-
random(0, 11, N), % generate random integer between 1 and 10.
name(N, Name).
My question would be: How do I get this in a list? And a list of exactly three elements at that?
I don't want to use too many built-ins. length/2 would be alright though. I think I might need it :)
Thanks a lot!
Edit: I figured I would first try to generate a list of three random numbers (the names can come later). I wrote this horribly wrong little thing:
numberlist([N|T]) :-
random(0, 11, N),
length([N|T], 3),
numberlist(T).
I know how to do this with a /2 predicate; when the user can just enter in the query that they want a list with three elements (numberlist(3,X).for example). But I'm can't seem to figure out how to write down in code that I always want a list of three numbers.
I was also thinking of using findall for generating my list, but again I don't know how to limit the length of the list to three random elements.
When describing lists in Prolog, it is often useful to first describe how a single element looks like.
For example, in your case, it seems you already have a predicate like random_name/1, and it describes a single element of the list you want to describe.
So, to describe a list consisting of three such elements, what about:
random_names([A,B,C]) :-
random_name(A),
random_name(B),
random_name(C).
This describes a list with three elements, and random_name/1 holds for each of these elements.

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|_].

Reverse the last two elements of a list in Prolog

I am trying to write the following predicate in Prolog while not making use of append/3:
lastTwoReversed(List, ListOf2)
which succeeds exactly when ListOf2 contains the last and the second-to-last elements of List in that order (i.e. reversed).
However, I don't know where to start. Any help is appreciated.
You can write a simple recursive predicate with a base case pattern matching on a list consisting of two elements like so:
last_two_reversed([X,Y],[Y,X]).
Since this is probably homework, I think it's best if you try to write the recursive clause yourself.
Simply use the built-in predicate reverse/2:
last_two_reversed([A,B|T],[Y,X]) :-
reverse([A,B|T],[Y,X|_]).
This will fail for lists with strictly less than two elements. A sensible thing to do would be to make it succeed using those two additional rules:
last_two_reversed([],[]).
last_two_reversed([H],[H]).
First of all, the predicate should fail or succeed with empty list or list with only one element??
In mathematical logic the predicate should return true with empty list and one-element list, because there are no last and second to-last elements to reverse.
So if you want to succeed with empty or one element list you should first start with :
lastTwoReversed([],[]).
lastTwoReversed([X],[X]).
(else don't write the above rules).
Next as base you should write:
lastTwoReversed([X,Y],[Y,X]).
and finally for list of length 3 or greater:
lastTwoReversed([X,Y,Z|T],[X|T1]):-lastTwoReversed([Y,Z|T],T1).
Keep in mind that we write [X,Y,Z|T] to specify for list with 3 or more elements so that doesn't match the previous rules.

OCAML - Is element in the list?

let's say we have a list of elements:
[(a,b); (c,d); (e,f)]
What function would check if element (lets say A, where A=(x,y)) is in the list or not?
Use List.mem to do the search for a match.
let a = (3,4)
List.mem a [(1,2); (3,4); (5,6)]
You can also use List.memq if you want to check if the two items both reference the same entity in memory.
Here's a hint on how to write this yourself. The natural way to to process a list is to initially look at the first element, then check the remainder of the list recursively until you have an empty list. For this problem, you could state the algorithm in English as follows:
If the list is empty then the item is not in the list,
else if the first list element equals the item then it is in,
else it is the answer to (Is the item in the remainder of the list?)
Now you just need to translate this into OCaml code (using a recursive function).
In general, if you can describe what you want to do in terms of smaller or simpler parts of the problem, then writing the recursive code is straightforward (although you have to be careful the base cases are correct). When using a list or tree-structured data the way to decompose the problem is usually obvious.