Scala 递归函数返回 Either
Scala recursive function returning Either
我正在编写一个递归函数,它 returns False 或一个值列表。
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1)
chars
else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) => {
if (are_equal(head, tail.head))
head :: tail
else if (are_cancelled(head, tail.head))
tail.tail
else
false
}
case Right(b) => false
}
}
}
我收到错误:value head is not a member of Either[List[Char],Boolean]
,但只能在匹配列表后使用 head 方法。
模式匹配 tail match { ... }
不会神奇地改变您匹配的值的类型。 tail
仍然是 Either
而 Either
没有成员 head
。但是l
是一个List
,所以把tail.head
换成l.head
等等。
您可以尝试插入显式类型注释以使事情更清楚。
您的 return 类型在一些地方也是错误的。这是一个更接近编译的版本:
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1) {
Left(chars)
} else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) =>
if (are_equal(head, l.head))
Left(head :: l)
else if (are_cancelled(head, l.head))
Left(l.tail)
else
Right(false)
case Right(b) => Right(false)
}
}
}
我正在编写一个递归函数,它 returns False 或一个值列表。
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1)
chars
else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) => {
if (are_equal(head, tail.head))
head :: tail
else if (are_cancelled(head, tail.head))
tail.tail
else
false
}
case Right(b) => false
}
}
}
我收到错误:value head is not a member of Either[List[Char],Boolean]
,但只能在匹配列表后使用 head 方法。
模式匹配 tail match { ... }
不会神奇地改变您匹配的值的类型。 tail
仍然是 Either
而 Either
没有成员 head
。但是l
是一个List
,所以把tail.head
换成l.head
等等。
您可以尝试插入显式类型注释以使事情更清楚。
您的 return 类型在一些地方也是错误的。这是一个更接近编译的版本:
def parse(chars: List[Char]): Either[List[Char], Boolean] = {
if (chars.length == 1) {
Left(chars)
} else {
val head = chars.head
val tail = parse(chars.tail)
tail match {
case Left(l) =>
if (are_equal(head, l.head))
Left(head :: l)
else if (are_cancelled(head, l.head))
Left(l.tail)
else
Right(false)
case Right(b) => Right(false)
}
}
}