Hi. Can anyone who know match types tell me why compiler says that it cannot find b?
Code
trait InfiniteSequence {
type L; type R;
val left: L; val right: R
}
class Cons [A, B <: InfiniteSequence](var a:A, var b:B) extends InfiniteSequence {
type L = A; type R = B; val left = a; val right = b;
}
object End extends InfiniteSequence {
type L = End.type; type R = End.type; val left = this; val right = this; }
type End = End.type
type _AdditionHelper[A <: InfiniteSequence, B <: InfiniteSequence] = B match {
case End => A
case Cons[a, b] => _AdditionHelper[Cons[a, B], b.R]
}
type Add[A <: InfiniteSequence, B <: InfiniteSequence] = _AdditionHelper[A, B]
type _RemoveHelper[Value, Checked <: InfiniteSequence, Remaining <: InfiniteSequence] = Remaining match {
case End => Checked
case Cons[t, p] => _RemoveHelper[Value, Cons[t, p], p.R]
case Cons[Value, p] => _RemoveHelper[Value, Checked, p.R]
}
type Remove[Value, Target <: InfiniteSequence] = _RemoveHelper[Value, End, Target]
type Z4 = Add[Cons[Nothing, Cons[Nothing, End]], Cons[Nothing, Cons[Nothing, End]]]
I guess because in b.R
, b
is always a value. While in case Cons[a, b]
, b
is a type. So there is a type b
, but the compiler cannot find a value b
.
1 Like
So I assume that I should use # to get the type, and I did but there is another error p is not a legal path since it is not a concrete type
which suggests that I cannot do recursion? Is there a way to make it work, I don’t know scala 3 well.
p
is an abstract type “variable” in the case clause.
It turns out that it was actually trivial. I could just use it like this:
trait InfiniteSequence {
type L; type R;
val left: L; val right: R
}
class Cons [A, B <: InfiniteSequence](var a:A, var b:B) extends InfiniteSequence {
type L = A; type R = B; val left = a; val right = b;
}
object End extends InfiniteSequence {
type L = End.type; type R = End.type; val left = this; val right = this; }
type End = End.type
type _AdditionHelper[A <: InfiniteSequence, B <: InfiniteSequence] = B match {
case End => A
case Cons[a, b] => _AdditionHelper[Cons[a, B], b]
}
type Add[A <: InfiniteSequence, B <: InfiniteSequence] = _AdditionHelper[A, B]
type _RemoveHelper[Value, Checked <: InfiniteSequence, Remaining <: InfiniteSequence] = Remaining match {
case End => Checked
case Cons[t, p] => _RemoveHelper[Value, Cons[t, p], p]
case Cons[Value, p] => _RemoveHelper[Value, Checked, p]
}
type Remove[Value, Target <: InfiniteSequence] = _RemoveHelper[Value, End, Target]
type Z4 = Add[Cons[Unit, Cons[Unit, End]], Cons[Unit, Cons[Unit, End]]]