refactoring based on  https://github.com/scalanlp/breeze/issues/145