Discovering modular solutions that generalize compositionally