Convert A String to List in Prolog

I am a Prolog newbie and am stuck at parsing a string to a list. I have a string of the form. I want to read polynomial as String and convert it into String.

I want to convert the input String

``2x^3 + x^2 - 4x^1 - 8``

to

``[[2,3], [1,2], [-4, 1], [-8, 0]]``

How can I achieve this functionality?

This problem is easily solved in two steps:

1. Lexical analysis / tokenizer: convert the string into a list of tokens that represent each of the possible elements of the expression: numbers, variable names and operators. The representations maybe, for instance, the terms `number(V)`, `vname(N)` and `op(Op)`; you may wish to use different terms for the additive operators that separate the monomials and for the exponent operator.
2. Syntactic analysis / parser: apply grammar rules to the list of tokens to identify monomials and convert them to the required representation. In this case each rule could have the form of a clause that inspects what appears at the beginning of the tokens list to find a monomial and convert it.
Sample rules could be

``````monom([number(N),vname(X),op(exp),number(E)|Ts],[[N,E]|Ms]) :-
!, monom(Ts,Ms).
monom([number(N),vname(X),op(+)|Ts],[[N,1]|Ms]) :-
!, monom([op(+)|Ts],Ms).
``````

Note that these rules do not check whether the variables have always the same name. Another issue is using the minus sign of a monomial. But I hope you will be able to cope with this.