Improved Scala solution