Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Last active February 5, 2024 05:53
Show Gist options
  • Save xuwei-k/b4a2c447ec47b32dcf4eff39ac3dcef1 to your computer and use it in GitHub Desktop.
Save xuwei-k/b4a2c447ec47b32dcf4eff39ac3dcef1 to your computer and use it in GitHub Desktop.
import scala.compiletime.ops.int.*
object MapTupleNExample {
type TupleMapN[T <: NonEmptyTuple, N <: Int, A] =
N < Tuple.Size[T] match {
case true =>
Tuple.Concat[
Tuple.Take[T, N],
A *: Tuple.Drop[T, N + 1]
]
}
final class Ops[N <: Int](val n: N) extends AnyVal {
def apply[T <: NonEmptyTuple, A](
tuple: T,
f: Tuple.Elem[T, N] => A
): TupleMapN[T, N, A] =
Tuple
.fromArray(
tuple.take(n).toArray ++ (f(
tuple(n).asInstanceOf[Tuple.Elem[T, N]]
).asInstanceOf[Object] +: tuple.drop(n + 1).toArray)
)
.asInstanceOf[TupleMapN[T, N, A]]
}
def tupleMapN[N <: Int](n: N): Ops[n.type] = new Ops[n.type](n)
def typed[A](a: A): Unit = ()
def main(args: Array[String]): Unit = {
val x1 = tupleMapN(0)((2, "a", false), _.toString)
typed[(String, String, Boolean)](x1)
println(x1)
assert(x1 == ("2", "a", false))
val x2 = tupleMapN(2)((2, "a", Option(3), false, List("x")), _.map(x => x :: Nil))
typed[(Int, String, Option[List[Int]], Boolean, List[String])](x2)
println(x2)
assert(x2 == (2, "a", Option(List(3)), false, List("x")))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment