Corrected logic errors in expansion derivation algorithms
Added type safety, now solution is a total function