Change the representation of optimized list of operation and add folding.

After optimization, an operation is a list of flatmap and something at
the end, so I changed it to be actually that.

I also added folding.