Scala3
def diffs(a: Seq[Long]): List[Long] =
a.drop(1).zip(a).map(_ - _).toList
def predictNext(a: Seq[Long], combine: (Seq[Long], Long) => Long): Long =
if a.forall(_ == 0) then 0 else combine(a, predictNext(diffs(a), combine))
def predictAllNexts(a: List[String], combine: (Seq[Long], Long) => Long): Long =
a.map(l => predictNext(l.split(raw"\s+").map(_.toLong), combine)).sum
def task1(a: List[String]): Long = predictAllNexts(a, _.last + _)
def task2(a: List[String]): Long = predictAllNexts(a, _.head - _)
Scala3