From 7241d7390a8403a58dd8d76465ab9f6d403c0644 Mon Sep 17 00:00:00 2001 From: scarf Date: Sat, 7 Dec 2024 23:39:48 +0900 Subject: [PATCH] refactor: extract functions --- 2024/day07.scala | 5 ----- prelude/iterable.scala | 10 +++++++++- prelude/math.scala | 3 +++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/2024/day07.scala b/2024/day07.scala index 844ce62..86390c4 100644 --- a/2024/day07.scala +++ b/2024/day07.scala @@ -3,14 +3,9 @@ package `2024`.day07 import prelude.* import scala.annotation.tailrec -def digits(x: Long) = math.log10(x.toDouble).toInt + 1 - extension (a: Long) inline def ||(b: Long) = (a * math.pow(10, digits(b)) + b).toLong -extension [C <: Iterable, A](xs: C[A]) - def orEmpty[B](f: C[A] => B)(els: => B) = if (xs.isEmpty) els else f(xs) - type Op = Long => Long => List[Long] def getCombo(xs: List[Long], next: Op) = diff --git a/prelude/iterable.scala b/prelude/iterable.scala index 0030bb6..e5251d1 100644 --- a/prelude/iterable.scala +++ b/prelude/iterable.scala @@ -13,4 +13,12 @@ extension [A](xs: IterableOnce[A]) * items.map(_.length).sum // 6 * }}} */ - inline def sumBy[B >: Int](f: A => B)(using Numeric[B]): B = xs.iterator.map(f).sum + inline def sumBy[B >: Int](f: A => B)(using Numeric[B]): B = + xs.iterator.map(f).sum + +extension [C <: Iterable, A](xs: C[A]) + /** Maps the iterable to a new iterable using the given function `f` if the + * iterable is not empty. Otherwise, returns the given value `default`. + */ + def orEmpty[B](f: C[A] => B)(default: => B) = + if (xs.isEmpty) default else f(xs) diff --git a/prelude/math.scala b/prelude/math.scala index b35003c..16b6cd2 100644 --- a/prelude/math.scala +++ b/prelude/math.scala @@ -1,5 +1,8 @@ package prelude +def digits(x: Int) = math.log10(x.toDouble).toInt + 1 +def digits(x: Long) = math.log10(x.toDouble).toInt + 1 + extension (n: Int) inline infix def divmod(d: Int) = (n / d, n % d) inline infix def moddiv(d: Int) = (n % d, n / d)