Code Generation

I have a question which I am having trouble figuring out.

assume I have the following function
gentype() = PP

assume I have a type as QQ{MM{gentype(){LL{Int}},Z}, NN{LL{Z}}} I want to transform it to another type
XQQ{XMM{PP{LL{Int}},XZ}, XNN{XLL{XZ}}} via generating the following code:

transformtype((transformtype(QQ)){transformtype((transformtype(MM)){transformtype((transformtype((transformtype(gentype))())){transformtype((transformtype(LL)){transformtype(Int)})}), transformtype(Z)}), transformtype((transformtype(NN)){transformtype((transformtype(LL)){transformtype(Z)})})})

As you see here,
PP{LL{Int}} hasn’t changed because the type is PP. The others types are transformed to their new versions. So my question is how can I do this at runtime. How does transformtype look like? What is its signature ? I assume I will need some sort of a state.

Or is there a better way to get this done?


transformtype((transformtype(QQ, state)){transformtype((transformtype(MM, state)){transformtype((transformtype((transformtype(gentype, state))(), state)){transformtype((transformtype(LL, state)){transformtype(Int, state)}, state)}, state), transformtype(Z, state)}, state), transformtype((transformtype(NN, state)){transformtype((transformtype(LL, state)){transformtype(Z, state)}, state)}, state)}, state))

where state includes transformed and untransformed versions of the types, so that the outer one selects and chains and updates the state. This should work.

Please quote your code and make an MWE.