Solves #40 in scala