|
| 1 | +import scala.annotation.tailrec |
| 2 | +type |@[F[+_], G[+_]] = [a] =>> F[a] | G[a] |
| 3 | + |
| 4 | +object Fix: |
| 5 | + opaque type T[+F[+_]] = ApplyFix.T[F] |
| 6 | + |
| 7 | + def apply[F[+_]](f: F[Fix[F]]): T[F] = ApplyFix(f) |
| 8 | + |
| 9 | + extension [F[+_]](fix: T[F]) |
| 10 | + def value: F[Fix[F]] = ApplyFix.unwrap(fix) |
| 11 | + |
| 12 | + object ApplyFix: |
| 13 | + opaque type T[+F[+_]] = F[Fix[F]] |
| 14 | + |
| 15 | + def apply[F[+_]](f: F[Fix[F]]): T[F] = f |
| 16 | + |
| 17 | + def unwrap[F[+_]](v: T[F]): F[Fix[F]] = v |
| 18 | + |
| 19 | +type Fix[+F[+_]] = Fix.T[F] |
| 20 | + |
| 21 | +final case class Cat[+R](name: String, fur: String, rest: R) |
| 22 | +object Cat: |
| 23 | + def of[R, F[+_]](name: String, fur: String, rest: Fix[F]): Fix[F |@ Cat] = Fix(new Cat(name, fur, rest)) |
| 24 | + |
| 25 | +final case class Dog[+R](name: String, size: Long, rest: R) |
| 26 | +object Dog: |
| 27 | + def of[R, F[+_]](name: String, size: Long, rest: Fix[F]): Fix[F |@ Dog] = Fix(new Dog(name, size, rest)) |
| 28 | + |
| 29 | +case object End: |
| 30 | + type f[+a] = End.type |
| 31 | + def apply() = Fix[f](End) |
| 32 | + |
| 33 | +object DropRed: |
| 34 | + @tailrec def dropRedCats[F[+a] >: Cat[a]](cats: Fix[F]): Fix[F] = |
| 35 | + cats.value match |
| 36 | + case Cat(_, "red", rest) => dropRedCats(rest) // error |
| 37 | + case _ => cats |
| 38 | + |
| 39 | + type CatDogVector = Vector[Either[Cat[Unit], Dog[Unit]]] |
| 40 | + type CatOrDogs[+a] = Cat[a] | Dog[a] | End.type |
| 41 | + |
| 42 | + extension (catDogs: Fix[CatOrDogs]) def toVector : CatDogVector = |
| 43 | + @tailrec def go(acc: CatDogVector, catDogs: Fix[CatOrDogs]) : CatDogVector = catDogs.value match |
| 44 | + case Cat(name, fur, rest) => go(acc :+ Left(Cat(name, fur, ())), rest) |
| 45 | + case Dog(name, size, rest) => go(acc :+ Right(Dog(name, size, ())), rest) |
| 46 | + case End => acc |
| 47 | + |
| 48 | + go(Vector(), catDogs) |
| 49 | + |
| 50 | + val x = |
| 51 | + Cat.of("lilly" , "red" , |
| 52 | + Cat.of("anya" , "red" , |
| 53 | + Cat.of("boris" , "black", |
| 54 | + Dog.of("mashka", 3 , |
| 55 | + Cat.of("manya" , "red" , |
| 56 | + End()))))) |
| 57 | + |
| 58 | + |
| 59 | + def main(args: Array[String]) = |
| 60 | + println(x.toVector) |
| 61 | + println(dropRedCats(x).toVector) |
0 commit comments