Skip to content

Instantly share code, notes, and snippets.

@nagat01
Created September 12, 2024 19:33
Show Gist options
  • Save nagat01/caeebd6cf1f601cf881ff11c2ef62d71 to your computer and use it in GitHub Desktop.
Save nagat01/caeebd6cf1f601cf881ff11c2ef62d71 to your computer and use it in GitHub Desktop.
import scala.compiletime.ops.int._
sealed trait Lst[+A, N <: Int]
case object Nil extends Lst[Nothing, 0]
case class Cons[+A, N <: Int](head: A, tail: Lst[A, N]) extends Lst[A, N + 1]
def map2[A, B, C, N <: Int](list1: Lst[A, N], list2: Lst[B, N])(f: (A, B) => C): Lst[C, N] =
(list1, list2) match
case (Nil, Nil) => Nil
case (Cons(h1, t1), Cons(h2, t2)) =>
Cons(f(h1, h2), map2(t1, t2)(f))
extension [A] (head: A)
def :: [N <: Int](tail: Lst[A, N]) = Cons(head, tail)
extension [A : Numeric, N <: Int](list1: Lst[A, N])
def + (list2: Lst[A, N]) = map2(list1, list2)(summon[Numeric[A]].plus)
@main def main =
val list1 = 1 :: 2 :: Nil
val list2 = 3 :: 4 :: Nil
println(list1 + list2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment