|
| 1 | +class Funs { |
| 2 | + sealed trait ->[A, B] |
| 3 | +} |
| 4 | + |
| 5 | +/** |
| 6 | + * Binary tree with leafs holding values of types `F[X]`, `F[Y]`, ... |
| 7 | + * The complete structure of the tree is expressed by the type `A`, using the tags for branches and leafs. |
| 8 | + * |
| 9 | + * @tparam <*> tag for branches |
| 10 | + * @tparam T tag for leafs. |
| 11 | + * @tparam F value type of leafs. Each leaf holds a value of type `F[T]`, for some type `T`. |
| 12 | + * @tparam A captures the complete structure of the tree |
| 13 | + */ |
| 14 | +enum Tree[<*>[_, _], T[_], F[_], A] { |
| 15 | + case Branch[<*>[_, _], T[_], F[_], A, B]( |
| 16 | + l: Tree[<*>, T, F, A], |
| 17 | + r: Tree[<*>, T, F, B], |
| 18 | + ) extends Tree[<*>, T, F, A <*> B] |
| 19 | + |
| 20 | + case Leaf[<*>[_, _], T[_], F[_], A]( |
| 21 | + value: F[A], |
| 22 | + ) extends Tree[<*>, T, F, T[A]] |
| 23 | + |
| 24 | + def <*>[B](that: Tree[<*>, T, F, B]): Tree[<*>, T, F, A <*> B] = |
| 25 | + Branch(this, that) |
| 26 | + |
| 27 | + def partition[G[_], H[_]]( |
| 28 | + f: [x] => F[x] => Either[G[x], H[x]], |
| 29 | + )(using |
| 30 | + funs: Funs, |
| 31 | + ): Partitioned[G, H, funs.->] = |
| 32 | + this match { |
| 33 | + case Leaf(a) => |
| 34 | + f(a) match |
| 35 | + case Left(a) => Partitioned.Left(Leaf(a)) |
| 36 | + case Right(a) => Partitioned.Right(Leaf(a)) |
| 37 | + case Branch(l, r) => |
| 38 | + import Partitioned.{Both, Left, Right} |
| 39 | + import l.Partitioned.{Both => LBoth, Left => LLeft, Right => LRight} |
| 40 | + import r.Partitioned.{Both => RBoth, Left => RLeft, Right => RRight} |
| 41 | + |
| 42 | + (l.partition(f), r.partition(f)) match |
| 43 | + case (LLeft(lg), RLeft(rg)) => Left(lg <*> rg) |
| 44 | + case (LLeft(lg), RRight(rh)) => Both(lg, rh) |
| 45 | + case (LLeft(lg), RBoth(rg, rh)) => Both(lg <*> rg, rh) |
| 46 | + case (LRight(lh), RLeft(rg)) => Both(rg, lh) |
| 47 | + case (LRight(lh), RRight(rh)) => Right(lh <*> rh) |
| 48 | + case (LRight(lh), RBoth(rg, rh)) => Both(rg, lh <*> rh) |
| 49 | + case (LBoth(lg, lh), RLeft(rg)) => Both(lg <*> rg, lh) |
| 50 | + case (LBoth(lg, lh), RRight(rh)) => Both(lg, lh <*> rh) |
| 51 | + case (LBoth(lg, lh), RBoth(rg, rh)) => Both(lg <*> rg, lh <*> rh) |
| 52 | + } |
| 53 | + |
| 54 | + // note that `->` is never even used, to keep this reproduction case small |
| 55 | + enum Partitioned[G[_], H[_], ->[_, _]] { |
| 56 | + case Left(value: Tree[<*>, T, G, A]) |
| 57 | + case Right(value: Tree[<*>, T, H, A]) |
| 58 | + case Both[G[_], H[_], X, Y, ->[_, _]]( |
| 59 | + l: Tree[<*>, T, G, X], |
| 60 | + r: Tree[<*>, T, H, Y], |
| 61 | + ) extends Partitioned[G, H, ->] |
| 62 | + } |
| 63 | +} |
0 commit comments