members() of a list - list

There is the the member(), but is there members() predicate?
Which accept two lists and checks/unifies if the elements in the one list are members of the other list?
members([2,4], [1,2,3,4,5]) => true
members([2,X], [1,2,3,4,5]) =probably=> [2,1];[2,3];[2,4];[2,5]
or probably it should behave like :
members([2,4], [1,2,3,4,5]) => member([2], [1,2,3,4,5]),member([4], [1,2,3,4,5])
I'm looking for the second interpretation, but the first non procedural implementation!
=====
second interpretation probably :
?- Y=[1,2,3,4,5],maplist( \X^(member(X,Y)),[2,4,5]).

Related

Prolog - list contains 2x element X

Let's assume we have alphabet {x,y} and I want to create a function, which returns true or false, whether the input list contains 2x symbol x after each other.
For example two([x,x,y]). returns true, while two([x,y,x]). returns false.
This is my function that I have so far:
two([Xs]) :- two(Xs, 0).
two([y|Xs], S) :- two(Xs, S).
two([x|Xs], S) :- oneX(Xs, S).
two([], S) :- S=1.
oneX([x|Xs], S) :- S1 is 1, two(Xs, M1).
oneX([y|Xs], S) :- two(Xs, S).
I use parameter S to determine, whether there were 2x x already (if so, parameter is 1, 0 else). This function however doesn't work as intended and always return false. Can you see what am I doing wrong?
You can use unification here and thus check if you can unify the first two items of the list with X, if not, you recurse on the list:
two([x, x|_]).
two([_|T]) :-
two(T).
The first clause thus checks if the first two items of the list are two consecutive xs. The second clause recurses on the tail of the list to look for another match by moving one step to the right of the list.

Understanding Prolog's empty lists

I am reading Bratko's Prolog: Programming for Artificial Intelligence. The easiest way for me to understand lists is visualising them as binary trees, which goes well. However, I am confused about the empty list []. It seems to me that it has two meanings.
When part of a list or enumeration, it is seen as an actual (empty) list element (because somewhere in the tree it is part of some Head), e.g. [a, []]
When it is the only item inside a Tail, it isn’t an element it literally is nothing, e.g. [a|[]]
My issue is that I do not see the logic behind 2. Why is it required for lists to have this possible ‘nothingness’ as a final tail? Simply because the trees have to be binary? Or is there another reason? (In other words, why is [] counted as an element in 1. but it isn't when it is in a Tail in 2?) Also, are there cases where the final (rightmost, deepest) final node of a tree is not ‘nothing’?
In other words, why is [] counted as an element in 1. but it isn't when it is in a Tail in 2?
Those are two different things. Lists in Prolog are (degenerate) binary trees, but also very much like a singly linked list in a language that has pointers, say C.
In C, you would have a struct with two members: the value, and a pointer to the next list element. Importantly, when the pointer to next points to a sentinel, this is the end of the list.
In Prolog, you have a functor with arity 2: ./2 that holds the value in the first argument, and the rest of the list in the second:
.(a, Rest)
The sentinel for a list in Prolog is the special []. This is not a list, it is the empty list! Traditionally, it is an atom, or a functor with arity 0, if you wish.
In your question:
[a, []] is actually .(a, .([], []))
[a|[]] is actually .(a, [])
which is why:
?- length([a,[]], N).
N = 2.
This is now a list with two elements, the first element is a, the second element is the empty list [].
?- [a|[]] = [a].
true.
This is a list with a single element, a. The [] at the tail just closes the list.
Question: what kind of list is .([], [])?
Also, are there cases where the final (rightmost, deepest) final node of a tree is not ‘nothing’?
Yes, you can leave a free variable there; then, you have a "hole" at the end of the list that you can fill later. Like this:
?- A = [a, a|Tail], % partial list with two 'a's and the Tail
B = [b,b], % proper list
Tail = B. % the tail of A is now B
A = [a, a, b, b], % we appended A and B without traversing A
Tail = B, B = [b, b].
You can also make circular lists, for example, a list with infinitely many x in it would be:
?- Xs = [x|Xs].
Xs = [x|Xs].
Is this useful? I don't know for sure. You could for example get a list that repeats a, b, c with a length of 7 like this:
?- ABCs = [a,b,c|ABCs], % a list that repeats "a, b, c" forever
length(L, 7), % a proper list of length 7
append(L, _, ABCs). % L is the first 7 elements of ABCs
ABCs = [a, b, c|ABCs],
L = [a, b, c, a, b, c, a].
In R at least many functions "recycle" shorter vectors, so this might be a valid use case.
See this answer for a discussion on difference lists, which is what A and Rest from the last example are usually called.
See this answer for implementation of a queue using difference lists.
Your confusion comes from the fact that lists are printed (and read) according to a special human-friendly format. Thus:
[a, b, c, d]
... is syntactic sugar for .(a, .(b, .(c, .(d, [])))).
The . predicate represents two values: the item stored in a list and a sublist. When [] is present in the data argument, it is printed as data.
In other words, this:
[[], []]
... is syntactic sugar for .([], .([], [])).
The last [] is not printed because in that context it does not need to. It is only used to mark the end of current list. Other [] are lists stored in the main list.
I understand that but I don't quite get why there is such a need for that final empty list.
The final empty list is a convention. It could be written empty or nil (like Lisp), but in Prolog this is denoted by the [] atom.
Note that in prolog, you can leave the sublist part uninstantiated, like in:
[a | T]
which is the same as:
.(a, T)
Those are known as difference lists.
Your understanding of 1. and 2. is correct -- where by "nothing" you mean, element-wise. Yes, an empty list has nothing (i.e. no elements) inside it.
The logic behind having a special sentinel value SENTINEL = [] to mark the end of a cons-cells chain, as in [1,2,3] = [1,2|[3]] = [1,2,3|SENTINEL] = .(1,.(2,.(3,SENTINEL))), as opposed to some ad-hoc encoding, like .(1,.(2,3)) = [1,2|3], is types consistency. We want the first field of a cons cell (or, in Prolog, the first argument of a . functored term) to always be treated as "a list's element", and the second -- as "a list". That's why [] in [1, []] counts as a list's element (as it appears as a 1st argument of a .-functored compound term), while the [] in [1 | []] does not (as it appears as a 2nd argument of such term).
Yes, the trees have to be binary -- i.e. the functor . as used to encode lists is binary -- and so what should we put there in the final node's tail field, that would signal to us that it is in fact the final node of the chain? It must be something, consistent and easily testable. And it must also represent the empty list, []. So it's only logical to use the representation of an empty list to represent the empty tail of a list.
And yes, having a non-[] final "tail" is perfectly valid, like in [1,2|3], which is a perfectly valid Prolog term -- it just isn't a representation of a list {1 2 3}, as understood by the rest of Prolog's built-ins.

Erlang for each list of lists

I want to make a new list that only contains the elements of the "list of lists" which have a length of 1.
The code that i provide gives a exception error: no function clause matching.
lists:foreach(fun(X) if length(X) =:= 1 -> [X] end, ListOfLists).
I am new to erlang, and I am having trouble finding an alternative way for writing this piece of code.
Can someone give me some advice on how to do so?
You can match in a list comprehension to get this quite naturally:
[L || L = [_] <- ListOfLists]
For example:
1> LoL = [[a], [b,c], d, [e], [f,g]].
[[a],[b,c],d,[e],[f,g]]
2> [L || L = [_] <- LoL].
[[a],[e]]
If you want the elements themselves (as in result [a, e] instead of [[a], [e]]) you can match on the element within the shape:
3> [L || [L] <- LoL].
[a,e]
Depending on the size of the lists contained within LoL, matching will be significantly faster than calling length/1 on every member. Calling length/1 and then testing the result requires traversing the entire list, returning a value, and then testing it. This is arbitrarily more overhead than checking if the second element of the list is a termination (in other words, if the "shape" of the data matches).
Regarding your attempt above...
As a newcomer to Erlang it might be helpful to become familiar with the basic functional list operations. They pop up over and over in functional (and logic) programming, and generally have the same names. "maps", "folds", "filters", "cons", "car" ("head" or "hd" or [X|_]), "cdr" ("tail" or "tl" or [_|X]), and so on.
Your original attempt:
lists:foreach(fun(X) if length(X) =:= 1 -> [X] end, ListOfLists).
This can't work because foreach/2 only returns ok, never any value. It is used only when you want to iterate over a list to get side-effects, not because you want to get a return value. For example, if I have a chat system the chat rooms have a list of current members, and broadcasting a message is really sending each chat message to each member in the list, I might do:
-spec broadcast(list(), unicode:chardata()) -> ok.
broadcast(Users, Message) ->
Forward = fun(User) -> send(User, Message) end,
lists:foreach(Forward, Users).
I don't care about the return value, really, and we aren't changing anything in the list Users or the Message. (Note that here we are using the anonymous function to capture the relevant state that it requires -- essentially currying out the Message value so we can present a function of arity 1 to the list operation foreach/2. This is where lambdas become most useful in Erlang vs named functions.)
When you want to take a list as an input and return a single, aggregate value (use some operation to roll all the values in the list into one) you can use a fold (you almost always want to use foldl/3, specifically):
4> lists:foldl(fun(X, A) when length(X) =:= 1 -> [X|A]; (_, A) -> A end, [], LoL).
[[e],[a]]
Broken down that reads as:
Single =
fun
(X, A) when length(X) =:= 1 -> [X|A];
(_, A) -> [X|A]
end,
ListOfSingles = lists:foldl(Single, [], LoL).
This is an anonymous function that has two clauses.
Written another way with a case we could do:
Single =
fun(X, A) ->
case length(X) of
1 -> [X|A];
_ -> A
end
end,
This is a matter of preference, as is the choice to inline that as an anonymous function within the call to foldl/3.
What you are really trying to do, though, is filter the list, and there is a universal list function called just that. You supply a testing function that returns a boolean -- if the test is true then the element will turn up in the output, otherwise it will not:
5> lists:filter(fun([X]) -> true; (_) -> false end, LoL).
[[a],[e]]
Breaking the lambda out as before:
6> Single =
6> fun([X]) -> true;
6> (_) -> false
6> end.
#Fun<erl_eval.6.54118792>
7> lists:filter(Single, LoL).
[[a],[e]]
Here we matched on the shape of the element in the anonymous function head. This filter is almost exactly equivalent to the list comprehension above (the only difference, really, is in the underlying implementation of list comprehensions -- semantically they are identical).

Prolog - 'Member Of' List

I have a function called member that is supposed to take as arguments:
1) a name
2) a list of names.
The list of names is already defined in my program, so I want to be able to call the method with a name and the list that's already initialized in the program.
For example, my Prolog program contains...
namesList(mike,joe,bob,jill).
member(Element, [Element|_]):-!.
member(Element, [_|Tail]):-member(Element,Tail).
So, when I'm at a Prolog prompt and type in member(mike,namesList). Prolog should output true, but instead prints false.
Am I calling the function correctly, or can I not use an already instantiated list?
First, Prolog doesn't have functions: it has predicates.
Second, A non-empty prolog list is written using square brackets — [a,b,c,d] with the empty list denoted by the atom []. Lists are actually represented by the structure ./2, where the first argument is the first item (the head) of the list and the second argument is the remainder of the list, either another non-empty list, or the empty list itself. It's what the compiler writers like to call syntactic sugar. So
[a] is exactly equivalent to .(a,[]).
[a,b] is exactly equivalent to .(a,.(b,[])).
[a,b,c] is exactly equivalent to .(a,.(b,.(c,[])))
etc.
And
[A|B] is exactly equivelent to .(A,B).
You can see why the square brackets notation is a little easier to use.
So...you could store your names list this:
names_list( [mike,joe,bob,jill] ).
in which case, you could say:
?- names_list( Names ) , member(mike,Names) .
true.
However...You might find it easier if you maintained your names in a more...prolog-like manner:
name( mike ) .
name( joe ) .
name( bob ) .
name( jill ) .
Then...
You can check for existence in the usual way:
?- N = sam , name(N) ,
false.
Or, you can iterate over them via backtracking:
?- name(N).
N = mike ;
N = joe ;
N = tim ;
N = jill.
And, if you really need them as a list, it's easy to get them in that form:
?- findall(N,name(N),Ns).
Ns = [mike, joe, tim, jill].
Finally, one should note the list of names could be extracted from your
names_list( mike , joe , bob , jill ).
but it's not exactly the most elegant thing in the world:
extract( Name , Arguments ) :-
atom(Name) ,
current_functor(Name,Arity) ,
length(Arguments,Arity) ,
Goal =.. [Name|Arguments] ,
callable(Goal) ,
call(Goal)
.
Once you have that, you can say:
?- extract(names_list,Names) , member(mike,Name).
true.

finding sublist in lists with map/select in mathematica

I have, in Wolfram Mathematica 8.0, a nested list like
nList = {{a,b},{f,g},{n,o}}
and a normal list like
lList = {a,b,c,k,m,n,o,z}
and i want to check if all the sublists in nList are in lList (in the example a,b and n,o are there but not f,g)
I've done it using For[,,,] and using index... can someone enlighten me in using functions like Map/Thread/Select to do it in one pass.
Edit: If nList contains a,b, lList must contain a,b and not a,c,b or b,a or b,c,a
Assuming that you don't care about element ordering, here is one way:
In[20]:= Complement[Flatten[nList],lList] ==={}
Out[20]= False
EDIT
If the order matters, then here is one way:
In[29]:= And##(MatchQ[lList,{___,PatternSequence[##],___}]&###nList)
Out[29]= False
For large number of sub-lists, this may be faster:
In[34]:=
Union[ReplaceList[lList,
{___,x:Alternatives##(PatternSequence###nList),___}:>{x}]]===Union[nList]
Out[34]= False
This works as follows: ReplaceList is a very nice but often ignored command which returns a list of all possible expressions which could be obtained with the pattern-matcher trying to apply the rules in all possible ways to an expression. This is in contrast with the way the pattern-matcher usually works, where it stops upon the first successful match. The PatternSequence is a relatively new addition to the Mathematica pattern language, which allows us to give an identity to a given sequence of expression, treating it as a pattern. This allowed us to construct the alternative pattern, so the resulting pattern is saying: the sequence of any sublist in any place in the main list is collected and put back to list braces, forming back the sublist. We get as many newly formed sublists as there are sequences of the original sublists in the larger list. If all sublists are present, then Union on the resulting list should be the same as Union of the original sublist list.
Here are the benchmarks (I took a list of integers, and overlapping sublists generated by Partition):
In[39]:= tst = Range[1000];
In[41]:= sub = Partition[tst, 2, 1];
In[43]:=
And ## (MatchQ[tst, {___, PatternSequence[##], ___}] & ### sub) // Timing
Out[43]= {3.094, True}
In[45]:=
Union[ReplaceList[tst, {___,x : Alternatives ## (PatternSequence ### sub), ___}
:> {x}]] === Union[sub] // Timing
Out[45]= {0.11, True}
Conceptually, the reason why the second method is faster is that it does its work in the single run through the list (performed internally by ReplaceList), while the first solution explicitly iterates through the big list for each sub-list.
EDIT 2 - Performance
If performance is really an issue, then the following code is yet much faster:
And ## (With[{part = Partition[lList, Length[#[[1]]], 1]},
Complement[#, part] === {}] & /#SplitBy[SortBy[nList, Length], Length])
For example, on our benchmarks:
In[54]:= And##(With[{part = Partition[tst,Length[#[[1]]],1]},
Complement[#,part]==={}]&/#SplitBy[SortBy[sub,Length],Length])//Timing
Out[54]= {0.,True}
EDIT 3
Per suggestion of #Mr.Wizard, the following performance improvement can be made:
Scan[
If[With[{part = Partition[lList, Length[#[[1]]], 1]},
Complement[#, part] =!= {}], Return[False]] &,
SplitBy[SortBy[nList, Length], Length]
] === Null
Here, the as soon as we get a negative answer from sub-lists of a given length, sublists of other lengths will not be checked, since we already know that the answer is negative (False). If Scan completes without Return, it will return Null, which will mean that lList contains all of the sublists in nList.
You could use pattern matching to do this job:
In[69]:= nList = {{a, b}, {f, g}, {n, o}};
lList = {a, b, c, k, m, n, o, z};
The ### is an alias for Apply at level {1}. The level 1 of nList contains your pairs, and applying replaces the head List in them with the function to the right of ###.
In[71]:= MatchQ[lList, {___, ##, ___}] & ### nList
Out[71]= {True, False, True}