Solves #29 in scala