Search code examples
prologpredicate

Split a list in prolog to atoms and integers


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]


Solution

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