Skip to content

Instantly share code, notes, and snippets.

@rohinp
Last active July 22, 2022 11:06
Show Gist options
  • Save rohinp/81c887c182be1a4a5c7bde8969070635 to your computer and use it in GitHub Desktop.
Save rohinp/81c887c182be1a4a5c7bde8969070635 to your computer and use it in GitHub Desktop.
object OddNumScala2 {
sealed trait Num
object Num {
case object Zero extends Num
case class Succ[N <: Num](num: N) extends Num
}
@implicitNotFound("Odd number type not satisfied.")
trait OddNum[N <: Num]
object OddNum {
import Num._
implicit val one = new OddNum[Succ[Zero.type]] {}
implicit def oddNumberPlusTwo[N <: Num: OddNum] =
new OddNum[Succ[Succ[N]]] {}
}
import Num._
def takeOnlyOdd[N <: Num: OddNum](oddNumber: N) = {
// do something
}
takeOnlyOdd(Zero) // does not compile for 0
takeOnlyOdd(Succ(Zero))
takeOnlyOdd(Succ(Succ(Zero))) // does not compile for 2
takeOnlyOdd(Succ(Succ(Succ(Zero))))
sealed abstract class List[+H, N <: Num](val size: N) {
def ::[T >: H](value: T): List[T, Succ[N]] = Cons(value, this)
}
case object Nil extends List[Nothing, Zero.type](Zero)
case class Cons[+H, N <: Num](head: H, tail: List[H, N])
extends List[H, Succ[N]](Succ(tail.size))
type ::[+H, N <: Num] = Cons[H, N]
def onlyOddSizeList[T, N <: Num: OddNum](
list: List[T, N]
) = {
// do something
}
onlyOddSizeList(1 :: 2 :: Nil) // error for even size list
onlyOddSizeList(1 :: 2 :: 3 :: Nil) // ok for odd size list
}
object OddNumScala3:
import scala.compiletime.ops.int.*
sealed trait List[+H, N <: Int]:
def ::[T >: H](value: T): List[T, S[N]] = List.Cons(value, this)
object List:
case object Nil extends List[Nothing, 0]
case class Cons[+H, N <: Int](head: H, tail: List[H, N])
extends List[H, S[N]]
end List
def takeOnlyOddLengthList[
T,
L <: Int & Singleton,
oddValidation >: (L % 2 >= 1) <: true
](x: List[T, L]): Unit = ()
import List._
val oddList: List[Int, 3] = 1 :: 1 :: 1 :: Nil
val evenList: List[Int, 2] = 1 :: 1 :: Nil
takeOnlyOddLengthList(oddList)
takeOnlyOddLengthList(evenList)
//does not compile
end OddNumScala3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment