Search code examples
listprologintegeratomic

Invert atoms from list to integers - Prolog


I have this:

streams=[[1,2,2,4],[2,1,4,2],[3,4,1,3],[4,3,3,1]]

And the numbers inside that lists are all atoms and I need to invert then all to integers. The streams should look like this:

streams=[[1,2,2,4],[2,1,4,2],[3,4,1,3],[4,3,3,1]]

But with all numbers with format 'integer' and not 'atom' Can someone explain how tranform those numbers to integers please?


Solution

  • To convert between atom and number you can use the built-in predicate atom_number/2:

    ?- atom_number(Atom, 1).
    Atom = '1'.
    
    ?- atom_number('1', Number).
    Number = 1.
    

    Using maplist/3, you can apply that convertion on all elements of a list of atoms:

    ?- maplist(atom_number, ['1','2','2','3'], Numbers).
    Numbers = [1, 2, 2, 3].
    

    To apply that convertion on all atoms in a list of lists you can do as follows:

    ?- maplist(maplist(atom_number), [['1','2'],['2','1','4'],['3'],['4','1']], ListOfLists).
    ListOfLists = [[1, 2], [2, 1, 4], [3], [4, 1]].