"Trains" exercise implemented in Scala