Reputation: 67
I am new to prolog and trying to make a predicate to separate a list in to atoms and integers but I have been try different ways for a while now but no where is there is an example on how this would be done. To me this seems like a basic thing to know in proleg yet there is no example that I can find on how this would be done.
eg: separate([3,t,8,l,0,a,5,g,2],Atoms,Integers). Atoms = [a,g,l,t], Integers = [0,2,5,3,8]
Upvotes: 0
Views: 400
Reputation: 74277
Especially if you're learning, roll your own. This also allows you to handle the edge cases. This, for instance, simply discards things other than atoms and integers:
atoms_and_ints( [] , [] , [] ) . % The empty list doesn't have any atoms or ints.
atoms_and_ints( [X|Xs] , [X|Atoms] , Ints ) :- % For a non-empty list,
atom(X), % - is the head an atom?
!, % - eliminate the choice point
atoms_and_ints(Xs,Atoms,Ints). % - add it to the atoms and recurse down.
atoms_and_ints( [X|Xs] , Atoms , [X|Ints] ) :- % Similarly,
integer(X), % - is the head an integer?
!, % - eliminate the choice point
atoms_and_ints(Xs,Atoms,Ints). % - if so, add it to the Ints and recurse down.
atoms_and_ints( [_|Xs], Atoms, Ints ) :- % If the head of the list is something else...
atoms_and_ints(Xs,Atoms,Ints). % - discard it and recurse down.
Upvotes: 0
Reputation: 22585
In swi-prolog, using partition/4
:
separate(List, Atoms, Integers):-
partition(integer, List, Integers, Atoms).
This assumes that every item in the list is either an integer or an atom
Sample run:
?- separate([3,t,8,l,0,a,5,g,2],Atoms,Integers).
Atoms = [t, l, a, g],
Integers = [3, 8, 0, 5, 2].
Upvotes: 1