I want to create a list with coefficients from a nested structure in prolog.
For example: (structure –> return value)
item(koeffizient(2), exponent(2), item(koeffizient(3), exponent(3))) –> [0,0,2,3]
item(koeffizient(5), exponent(0), item(koeffizient(1), exponent(1), item(koeffizient(3), exponent(3)))) –> [5,1,0,3]
item(koeffizient(5), exponent(0)) –> [5]
item(koeffizient(5), exponent(0), item(koeffizient(2), exponent(2))) –> [5,0,2]
How can i do this in a recursive way? Actually i have no idea how i can do this.
Thank’s for any help you can give me =)
First note that is not a good idea to use a recursive structure the way you have it defined, as it differentiates the last item from the others.
You can do it greedily, assuming that your structure is ordered by the exponents (as your examples show):
Procedure
structure/2just callsstructure/3with exponent 0.The first clause of
structure/3is the base case. It returns the coefficient for the last exponent.The second clause matches the base case when the current exponent does not match. So in this case we return a zero as the next coefficient, increments the current exponent and applies recursion.
The third clause matches the recursive case when the current exponent matches the current exponent of the structure. So it returns the corresponding coefficient, increments the current exponent and applies recursion again.
The last clause is like the second clause but applies to input structures that still have more items left (apart from the current one).
If, as your comments say the input is not ordered then it might be better to transform your input to a list of ordered tuples of the form Exp-Coeff.
With such list, your
structure/2procedure remains the same and you can symplifyprocedure/3to this one: